我有一个非常基本的问题我有一个 JSON 数组,我可以使用const [elements, setElements] = useState([]); useEffect(() => { const res = async () => { const result = await axios.get('/data'); const data = result.data; setElements(elements => [...elements, ...data]); }; res(); }, []);我想将它们转换为基于类的组件,当我尝试在 setState 中复制时,我得到 []。代码如下import React, { Component } from 'react';import './App.css';import axios from 'axios';import Element from './components/Element';class App extends Component { constructor(props) { super(props); this.state = { elements: [] }; } componentDidMount() { const res = async () => { const result = await axios.get('/data'); const data = result.data; console.log(data); this.setState({ elements: data }); }; res(); } render() { console.log(this.state.elements); return ( <div className='wrapper'> <div id='table'> {this.state.elements.map(element => ( <Element elements={element} key={element._id} /> ))} </div> </div> ); }}export default App;这是我得到的 JSON(119) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, …]
2 回答
MMMHUHU
TA贡献1834条经验 获得超8个赞
问题在于您如何尝试在 React 组件上设置状态,也许您可以尝试以下操作:
this.setState({ elements: data});
您可以尝试将您componentDidMount()的更新为以下内容:
async componentDidMount() {
const {data} = await Axios.get('/data');
this.setState({ elements: data });
}
希望这有帮助!
子衿沉夜
TA贡献1828条经验 获得超3个赞
为了使代码相等,应该这样写
this.setState(state => ({
elements: [...state.elements, ...data]
}));
添加回答
举报
0/150
提交
取消