javascript - 做出反应。无法在 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
}
解决方案
getDerivedStateFromProps
是类的静态属性(如static
前面的关键字所示)。这意味着它无权访问任何实例函数/属性。
也将您声明getTodosList
为静态(如果它也不使用任何实例属性),然后调用Chart.getTodosList(todos)
.
编辑:
如果您调用setState
in getTodosList
,您可以将其更改为返回状态对象,然后您可以根据调用函数返回的对象构造/更新您的状态。
例如。
static getTodosList = todos => {
...
return { someState: someData }; //instead of this.setState({ someState });
}
static getDerivedStateFromProps() {
...
return Chart.getTodosList(todos);
}
如果componentDidMount
它与getDerivedStateFromProps
.
推荐阅读
- bash - 将脚本分配给包装脚本的变量
- android - 如何在 QAndroidjniobject 中传递参数?
- postgresql - 将 SQL 转换为 Arel - 列 [...] 必须出现在 GROUP BY 子句中
- android - 从 SDK 库代码中确定应用程序的构建变体
- javascript - 数组通过javascript
- python-3.x - 使用python将列表中的值从数据框存储到数据库中
- javascript - 如何使用角度将列标题包装在 ag-grid 中
- r - R数据框中多列的百分比分组
- python - Django - 我的套接字的路径对于 nginx 配置是否正确
- javascript - 如何在 svg 地图底部为鼠标悬停的每个城市添加描述框?