【问题标题】:Warning: Can't call setState (or forceUpdate) on an unmounted component in React Native警告:无法在 React Native 中的未安装组件上调用 setState(或 forceUpdate)
【发布时间】:2019-01-26 13:10:03
【问题描述】:

完整的错误图片: error image

我正在发出提取请求,并且当我想设置状态以保存发生的一些错误时。我该如何解决这个问题?

代码:

    onClickLogIn = (username, password) => {
    const request = fetch('[SOMEAPILINK]', {
    method: 'POST',
    headers: {
        Accept: 'text/javascript',
        'Content-Type': 'text/javascript',
    },
    body: JSON.stringify({
        username: username,
        password: password,
        login: 1
    })
    }).then(response => response.json()).then(responseJson => {   
        console.log(responseJson)
        this.setState({
            errorCheck: responseJson.error
        })
    }).catch(error => {
        console.log("error")
    })
    // console.log(errorCheck);
    console.log(request); 
    console.log("----ERROR CHECK ----")
    console.log(this.state.errorCheck)
    this.props.navigation.navigate("Second")

}

所以当我想设置 errorCheck 时,错误就进来了……

谢谢!

【问题讨论】:

  • 我的理解是,您正在登录屏幕并进行 API 调用以检查凭据。如果 Api 响应成功,您将导航到第二个屏幕,否则您将设置错误状态并显示它。是这样吗?
  • 是的,这是正确的,问题已经得到了正确的回答。

标签: javascript react-native fetch state


【解决方案1】:

setState 是异步的。因此,如果您在更新状态之前卸载有状态组件(通过调用导航),那么您将收到警告。

您应该改用setState 提供的回调

.then(response => response.json()).then(responseJson => {   
        console.log(responseJson)
        this.setState({
            errorCheck: responseJson.error
        }, () => {
    this.props.navigation.navigate("Second")
        })

})

【讨论】:

    【解决方案2】:
    then(response => response.json()).then(responseJson => {   
        console.log(responseJson)
        this.setState({
            errorCheck: responseJson.error
        })
        this.props.navigation.navigate("Second")
    })
    

    => 在then() 方法中添加此导航代码this.props.navigation.navigate("Second"),以便在更新state 后调用导航,然后您的错误就会消失。

    => 并尝试使用setState 更新state 函数 不是对象 所以试试

        this.setState(function (prevState, props) {
            return { errorCheck: responseJson.error}
        })
    

    它将减少对象更新状态所花费的时间。

    => 所以你的代码看起来像

      then(response => response.json()).then(responseJson => {   
        console.log(responseJson)
        this.setState(function (prevState, props) {
            return { errorCheck: responseJson.error}
        })
        this.props.navigation.navigate("Second")
    })
    

    【讨论】:

    • 我知道我不应该写谢谢 cmets 但你是救生员!
    • 我做了,但我没有 15 声望,所以它不会显示在屏幕上。
    • 如何确保在状态更新后调用navigate函数?你对此没有任何保证? github.com/facebook/react/issues/11527#issuecomment-360199710@JayThummar.
    • 是的,不能保证这就是为什么我建议使用函数更新状态..所以它更新得很快。如果我们谈论这个特殊的问题,Luka 将导航代码写在响应检查之外,这样这将首先调用导航,然后响应将到来并调用 setSate,此时组件不在前台,所以错误发生未安装的组件。
    猜你喜欢
    • 2019-03-10
    • 2018-11-03
    • 2019-08-23
    • 2019-01-07
    • 1970-01-01
    • 2023-04-08
    • 2019-02-11
    • 2018-10-28
    • 2016-10-01
    相关资源
    最近更新 更多