![](/img/trans.png)
[英]React Intercept component unmounting (Functional and Class Components)
[英]Conversion of functional components in react into class based component
我有一個非常基本的問題,我有一系列 JSON,我可以使用
const [elements, setElements] = useState([]);
useEffect(() => {
const res = async () => {
const result = await axios.get('/data');
const data = result.data;
setElements(elements => [...elements, ...data]);
};
res();
}, []);
我想將它們轉換為基於 class 的組件,當我嘗試在 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) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, …]
問題在於您如何嘗試在 React 組件上設置 state,也許您可以嘗試以下操作:
this.setState({ elements: data});
您可以嘗試將您的componentDidMount()
更新為以下內容:
async componentDidMount() {
const {data} = await Axios.get('/data');
this.setState({ elements: data });
}
希望這會有所幫助!
為了使代碼相等,應該這樣寫
this.setState(state => ({
elements: [...state.elements, ...data]
}));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.