setState()导致状态变量未定义

问题描述 投票:-1回答:1

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

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

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

这是由我的componentDidMount中的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。同样,我可以看到请求在开发人员工具的“网络”选项卡中按预期进行。

这可能会出错?为什么状态不正确更新w /返回的JSON?

reactjs
1个回答
2
投票

正如评论中所提到的,教程有一个拼写错误,这意味着代码试图访问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 }));
}
© www.soinside.com 2019 - 2024. All rights reserved.