ReactJS:解析错误:意外的令牌


class PostIndex extends Component {
//define state
const [posts, setPosts] = useState([]);
//useEffect hook
useEffect(() => {
//panggil method "fetchData"
fectData();
}, []);
//function "fetchData"
const fectData = async () => {
//fetching
const response = await axios.get('http://localhost:3000/api/posts');
//get response data
const data = await response.data.data;
//assign response data to state "posts"
setPosts(data);

}
}

export default PostIndex;

请帮助我,我在react js新学习。我是关于使类名称PostIndex,所以我从函数PostIndex()更改为类PostIndex扩展组件。从这一行得到误差const [posts, setPosts] = useState([]);你能帮我吗?请。由于

你不能在react钩子中使用react类组件。

所以正确的解决方案应该是这样的:

const PostIndex = () => {
//define state
const [posts, setPosts] = useState([]);
//useEffect hook
useEffect(() => {
//panggil method "fetchData"
fectData();
}, []);
//function "fetchData"
const fectData = async () => {
//fetching
const response = await axios.get('http://localhost:3000/api/posts');
//get response data
const data = await response.data.data;
//assign response data to state "posts"
setPosts(data);
}
return your markup
}

你不能在类组件中使用钩子,而应该使用函数式组件:

const PostIndex = () => {
const [posts, setPosts] = useState([]);
// rest of your code....
}
export default PostIndex;

你不能在类组件中使用像useState这样的React hook。它只适用于功能组件。如果你想在类组件中使用state,请按照如下方式:

class PostIndex extends React.Component {
state = {posts: []}; // define state
.....
this.setState({
posts: ['a', 'b']
}); // set state
.....
let temp = this.state.posts; // use state
.....
我希望这对你有帮助。谢谢。

最新更新