首页 > 解决方案 > setState() 导致状态变量未定义

问题描述

在大多数情况下,我遵循教程。

我的 Django API 设置得很好。我有这个服务功能:

export default class GoalService{
    getGoals() {
        const url = `${API_URL}/api/goals`;
        return axios.get(url).then(response => response.data);
    } 
}

componentDidMount由my中的方法调用GoalList

class GoalTable extends Component {
    constructor(props) {
        super(props);
        this.state = {
            goals: [],
            now: now.getDate(),
        }
    }

    componentDidMount() {
        var  self  =  this;
        goalService.getGoals().then(function (result) {
            console.log(result);
            self.setState({ goals: result.data })
        });
    }

    render() { ... }

(这是上述链接教程的第 8 步)。

现在,当我尝试使用时{ this.state.goals.map(...) },我得到了错误TypeError: this.state.goals is undefined。看看其他线程,很多人似乎都遇到过这个问题——但它的出现是因为他们在发出的请求setState() 之外setState()使用过,而且由于是异步的,所以状态被设置为空白。我在对 的调用中使用它then,所以我认为这不是问题。

我尝试添加第二个参数then(以防此操作不成功),但是,getGoals()调用成功,成功打印出 Django API 发回的 JSON。同样,我可以在开发人员工具的“网络”选项卡中看到请求按预期进行。

这里可能出了什么问题?为什么状态没有正确更新返回的 JSON?

标签: reactjs

解决方案


正如评论中提到的,教程有一个错字,这意味着代码尝试访问response.data.data而不是response.data.

解决方法是删除对对象的这种额外级别的钻取:

componentDidMount() {
    var self = this;
    goalService.getGoals().then(function (result) {
        self.setState({ goals: result }) // no .data
    });
}

另外,请注意,您可以通过使用箭头函数(自动this从定义它们的位置绑定 )和对象初始化简写来简化此代码:

componentDidMount() {
    // { goals } is the same as { goals: goals }
    goalService.getGoals().then(goals => this.setState({ goals }));
}

推荐阅读