首页 > 解决方案 > 做出反应。无法在 getDerivedStateFromProps 中启动函数

问题描述

我不明白,为什么当我尝试在方法getTodosList内启动函数时getDerivedStateFromProps- 它总是返回给我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

    }

标签: javascriptreactjs

解决方案


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

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

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

例如。

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

如果componentDidMount它与getDerivedStateFromProps.


推荐阅读