我有一个非常基本的问题我有一个 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) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, …]
MMMHUHU
子衿沉夜
相关分类