简单的 reactjs 组件具有意外的令牌错误



这个反应组件中的错误是什么?

import React, { useState, useEffect } from 'react';
import axios from 'axios';
const Tasks = () => {
const [tasks, setTasks] = useState([]);
useEffect(() => {
axios.get('/tasks').then(response => setTasks(response.data));
return (
<ul>
{renderList(tasks)}
</ul>
);
},[]);
};
renderList(tasks) {
console.log(tasks)
return <li>dd</li>
}
export default Tasks;

我无法弄清楚错误..似乎很容易,但我不知道我的错误在哪里。

./src/compononents/Tasks.js
Line 16:  Parsing error: Unexpected token, expected ";"
14 | };
15 | 
> 16 | renderList(tasks) {
|                   ^
17 |   console.log(tasks)
18 |   return <li>dd</li>
19 | }

这个反应组件中的错误是什么?

问题是该方法在组件之外,而且,返回应该在useEffect之外。

// component scope
const Tasks = () => {
const [tasks, setTasks] = useState([]);
useEffect(() => {
axios.get('/tasks').then(response => setTasks(response.data));
// can't return JSX inside useEffect
return (
<ul>
{renderList(tasks)}
</ul>
);
},[]);
};
// component scope
// outside component scope
renderList(tasks) {
console.log(tasks)
return <li>dd</li>
}

这是完整的工作代码

const Tasks = () => {
const [tasks, setTasks] = useState([]);
useEffect(() => {
axios.get('/tasks').then(response => setTasks(response.data));        
},[]);
const renderList = tasks => {
console.log(tasks)
return tasks.map(() => <li>dd</li>)
}
return (
<ul>
{renderList(tasks)}
</ul>
);
};

但是你可以让它更简单,比如

const Tasks = () => {
const [tasks, setTasks] = useState([]);
useEffect(() => {
axios.get('/tasks').then(response => setTasks(response.data));        
},[]);
return (
<ul>
{tasks.map(() => <li>dd</li>)}
</ul>
);
};

您无法从useEffect返回JSX

useEffect(() => {
axios.get('/tasks').then(response => setTasks(response.data));
},[])
return (tasks.length && <ul>{tasks.map(/*...*/)}</ul>)

useEffect只会返回一个函数来清理。考虑使用boolean有条件地在render内呈现JSX

相关内容

  • 没有找到相关文章

最新更新