javascript - 如何将状态中的值作为参数传递给函数?
问题描述
我一直在试图弄清楚如何将值从状态(personId)传递给函数(fetchPersonInfo)作为参数,但我尝试过的任何方法都没有奏效。所以我想来请你帮忙。
class Page extends Component {
state = {
personId: '',
}
componentDidUpdate = () => {
if(this.props.results.length > 0 && this.state.personId !== this.props.results[0].results[0].id){
if(this.props.results[0].results[0].media_type === 'person'){
this.setState({personId: this.props.results[0].results[0].id});
this.personInfo(personId);
}
}
}
personInfo = (personId) => {
if(this.state.personId.length > 0){
this.props.fetchPersonInfo(personId);
}
}
}
解决方案
ReactsetState
是异步的,你不能personInfo()
像你正在做的那样以同步的方式调用
this.setState({personId: this.props.results[0].results[0].id});
this.personInfo(personId);
假设其余代码没问题,将上面的代码更改为
this.setState({personId: this.props.results[0].results[0].id}, this.personInfo);
并从函数中删除 personId 参数
personInfo = () => {
if(this.state.personId){
this.props.fetchPersonInfo(this.state.personId);
}
}
推荐阅读
- google-maps-api-3 - Google Maps Javascript API - places.AutocompleteService - getPlacePredictions 在满足某些条件时返回错误的距离米
- c++ - 在 C++ 运算符重载中将友元函数更改为成员函数后的问题
- bing-maps - 如何在 bing 地图中从 snap 的 json 响应到 bing 的道路 api 绘制路线
- javascript - 按钮功能在使用外部组件的 React Hooks 中不起作用
- c - C socket编程客户端有时收不到服务器消息
- javascript - 打开一个新选项卡并听取其 URL 更改
- xml - 将内容分配给材料选项卡
- three.js - 使用 dat.gui 在 Three.js 中设置对象的位置
- react-native - React Native - 按下按钮“NativeAnimatedModule.startOperationBatch 不是函数”
- c# - SerialPort 实际上并没有打开 VirtualCOM 端口