【发布时间】:2021-08-25 16:19:52
【问题描述】:
我不明白在我想要做事情的情况下使用 useEffect 的必要性,例如在渲染之前。 例如,在下面的代码中,我想用信息填充数据,例如通过从 API 接收。现在下面代码的区别:
const Product_List = (props) => {
const [data, setData] = useState();
getData((response)=> setData(response));
return(
<FlatList
data={data}
/>
)
}
使用以下代码:
const Product_List = (props) => {
const [data, setData] = useState();
useEffect(() => {
getData((response)=> setData(response));
}, []);
return(
<FlatList
data={data}
/>
)
}
换句话说,这段代码不同:
class Product_List extends Component{
constructor(props) {
this.state = {
data: []
}
getData((response)=> this.setState({data: response}));
}
render(){
return(
<FlatList
data={data}
/>
)
}
}
使用以下代码:
class Product_List extends Component{
constructor(props) {
this.state = {
data: []
}
}
componentDidMount(){
getData((response)=> this.setState({data: response}));
}
render(){
return(
<FlatList
data={data}
/>
)
}
}
【问题讨论】:
-
函数体 != 类构造函数。而是 Function body == Class 渲染方法。
标签: javascript reactjs react-native react-hooks