我无法理解,为什么当我尝试在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
}
答案 0 :(得分:2)
getDerivedStateFromProps
是类的静态属性(由前面的static
关键字指示)。这意味着它无法访问任何实例函数/属性。
将您的getTodosList
声明为静态(如果它也不使用任何实例属性),则调用Chart.getTodosList(todos)
。
修改强>:
如果在setState
中调用getTodosList
,则可以将其更改为返回状态对象,然后根据调用函数返回的对象构建/更新状态。
例如
static getTodosList = todos => {
...
return { someState: someData }; //instead of this.setState({ someState });
}
static getDerivedStateFromProps() {
...
return Chart.getTodosList(todos);
}
如果它与componentDidMount
做同样的事情,您也不需要getDerivedStateFromProps
。
答案 1 :(得分:1)
getDerivedStateFromProps
是一个静态方法,它不能访问任何实例属性/方法,意味着this
在该方法中不可用。
使用componentDidUpdate
执行状态/道具更改所需的操作。
您需要在prevState / prevProps与新值之间进行检查。
componentDidUpdate(prevProps, prevState, snapshot) {
// compare this.state and prevState or compare the props values
// and perform the operation
}