首页 > 解决方案 > 如何将状态中的值作为参数传递给函数?

问题描述

我一直在试图弄清楚如何将值从状态(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);
        }
    }
}

标签: javascriptreactjsredux

解决方案


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);
    }
}

推荐阅读