ReactNative:this.setState错误:null不是对象

时间:2016-11-14 14:41:20

标签: reactjs react-native

反应脚本

class TransactionsList extends Component {
    constructor(props) {
        super(props);
        this.state = {
            activeAccountId: "",
            accessToken: "",
            TransactionsData: "",
        };
    }
    replaceRoute(route, passProps) {
        this.props.replaceRoute(route, passProps);
    }
    async _getToken() {
        try {
            let accessToken = await AsyncStorage.getItem('AUTH_TOKEN');
            if(!accessToken) {
                this.replaceRoute('login');
            } else {
                this.setState({accessToken: accessToken})
            }
        } catch(error) {
            Alert.alert('Print Errorr', error.message)
            this.replaceRoute('login');
        }
    }
    componentWillMount(){
        this._getToken()
        let token = 'Token '+this.state.accessToken
        this.load_data(token)
    }
    render() {
        return (
            <Container>
            // other code
            </Container>
        )
    }
}

getToken中setState中的错误是catch(错误)块输出

  

打印错误null不是对象(评估   prevComponentInstance._currentElement)

但上述代码在其他屏幕中也适用。

3 个答案:

答案 0 :(得分:1)

不建议在componentWillMount中进行api调用,因为当api调用结束并且您调用setState时,可能无法安装该组件。

相反,您应该在componentDidMount中进行api调用。根据{{​​3}}:

  

componentDidMount()在组件出现后立即调用   安装。需要DOM节点的初始化应该放在这里。如果你   需要从远程端点加载数据,这是一个好地方   实例化网络请求。在这种方法中设置状态会   触发重新渲染。

并且,您还需要将_getToken绑定为@Jazib提及。

答案 1 :(得分:0)

您需要使用以下内容绑定_getToken方法:

this._getToken().bind(this)

或者您可以在构造函数中执行此操作以获得更好的代码(我更喜欢这个代码):

constructor(props) {
    super(props);
    this.state = {
        activeAccountId: "",
        accessToken: "",
        TransactionsData: "",
    };
    this._getToken() = this._getToken().bind(this)
}

希望这有帮助

答案 2 :(得分:0)

我知道我的回复有点晚,但是更好的方法是使用箭头函数,而不是在命名函数上使用bind。因此,您可以这样编写_getToken方法:

const _getToken = async () => { // your logic here }

这里的arrow函数将组件的当前实例隐式分配给this关键字,而在命名函数中,您必须使用上述的this方法为bind关键字提供上下文被其他人

此外,componentWillMount现在已被弃用,如果您在componentDidMount中调用方法,它会更好。

相关问题