无法多次调用componentWillMount()中的setState,解决方法是React Native

时间:2018-08-31 12:52:52

标签: javascript react-native state

所以我有fetch()可以给我一个数组。因此,我将该数组存储在状态中,然后执行一些功能,完成后我想再次设置状态,以便停止加载。这是可以更好地解释它的代码(所有这些代码都在componentWillMount()btw中):

// before this is just simple unimportant get request
.then(responseJson => {
            // loading here is 1
            this.setState(function (prevState, props) {
                return {questions: responseJson}
            })

            this.makeAnswers(responseJson)

            // loading needs to be 0 here

        })

如果您需要更多信息,请发表评论。

谢谢!

2 个答案:

答案 0 :(得分:1)

为什么不将this.setState({loading: 0})放在makeAnswers()函数中?

只需检查是否需要这样做:

makeAnswers = (response) => {
  ...
  if (this.state.loading !== 0) this.setState({loading: 0})
}

答案 1 :(得分:0)

您可能只需要在调用makeAnswers函数之前等待第一个setState的承诺即可。

.then(async response => {
        // This will ensure questions is set in the state before calling makeAnswers
        await this.setState({questions: response.questions})

        this.makeAnswers(response.questions)

        this.setState({ loading: false })

    })

如果还要在makeAnswers中设置状态,则可以在其中设置加载状态。喜欢

    componentDidMount = () => {
        fetch()
        .then(async response => {
            // This will ensure questions is set in the state before calling makeAnswers
            await this.setState({questions: response.questions})
            this.makeAnswers(response.questions)

        })
    }


    makeAnswers = questions => {
        //...do something 
        this.setState({ answers: something, loading: false })
    }