【问题标题】:React. Cannot start function inside the getDerivedStateFromProps做出反应。无法在 getDerivedStateFromProps 中启动函数
【发布时间】:2018-04-27 05:59:42
【问题描述】:

我不明白,为什么当我尝试在 getDerivedStateFromProps 方法中启动函数 getTodosList 时 - 它总是返回给我 TypeError - Cannot read property 'getTodosList' of null

在我开始使用getDerivedStateFromProps 之后,我的函数也没有在componentDidMount 中启动...

我做错了什么? (

import React, { Component } from 'react';
import {Doughnut} from 'react-chartjs-2';

class Chart extends Component {
    constructor(props) {
        super(props);

        this.state = {
            // some state...
    }

    getTodosList = (todos) => {
        console.log(todos);
        const all = [];
        const done = [];

        // some logic...

    }

    componentDidMount() {
        const { todos } = this.props.state.iteams;
        console.log('componentDidMount', todos);

        this.getTodosList(todos);
    }

    static getDerivedStateFromProps(nextProps, prevState) {
        const { todos } = nextProps.state.iteams;
        console.log(this.getTodosList, prevState.datasets, 'componentWillReceiveProps', todos);

        this.getTodosList(todos); // TypeError: Cannot read property 'getTodosList' of null

    }

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    getDerivedStateFromProps 是类的静态属性(如前面的static 关键字所示)。这意味着它无权访问任何实例函数/属性。

    将您的getTodosList 也声明为静态(如果它也不使用任何实例属性)然后调用Chart.getTodosList(todos)

    编辑
    如果您在getTodosList 中调用setState,则可以将其更改为返回状态对象,然后您可以根据调用函数返回的对象构造/更新您的状态。

    例如。

    static getTodosList = todos => {
      ...
      return { someState: someData }; //instead of this.setState({ someState });
    }
    static getDerivedStateFromProps() {
      ...
      return Chart.getTodosList(todos);
    }
    

    如果componentDidMountgetDerivedStateFromProps 做同样的事情,您也不需要它。

    【讨论】:

    • 如果我将 getTodosList 设为 static - 我开始在其中的 this.setState({}) 中收到错误 TypeError: _this2.setState is not a function
    • 这就是我提到的,静态函数无法访问this 实例。让它返回状态对象而不是在其中调用setState,然后您可以根据调用函数返回的对象构造/更新您的状态。
    【解决方案2】:

    getDerivedStateFromProps 是一个静态方法,它不会访问任何实例属性/方法,这意味着this 在该方法中不可用。

    使用componentDidUpdate 对状态/道具更改执行您想要的操作。

    您需要在 prevState/prevProps 与新值之间进行检查。

    componentDidUpdate(prevProps, prevState, snapshot) {
       // compare this.state and prevState or compare the props values 
       // and perform the operation
    }
    

    【讨论】:

    • 如果我对这个组件使用componentDidUpdate,而不是getDerivedStateFromProps - 我陷入了stackoverflow循环
    • 当您不会在上一个值和新值之间进行检查时,这是正确的。在值之间使用条件然后只执行所需的操作,检查更新的答案。
    猜你喜欢
    • 2021-05-08
    • 1970-01-01
    • 2016-12-23
    • 2018-09-09
    • 2019-10-07
    • 2021-12-30
    • 1970-01-01
    • 2022-06-30
    • 1970-01-01
    相关资源
    最近更新 更多