这个反应组件中的错误是什么?
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