gpt4 book ai didi

javascript - 在 ReactStore 方法中绑定(bind) Scope 以使用 setState()

转载 作者:行者123 更新时间:2023-12-01 03:01:56 26 4
gpt4 key购买 nike

我正在尝试通过 setState() 更新 StoreState;方法,我收到一个“this.setState() is undefined”,在我看来就像范围界定问题。

我正在尝试将范围绑定(bind)到函数以从此方法设置存储状态(请参阅构造函数或 AppDispatcher 中)但它没有成功。所以我想我必须以不同的方式/在其他地方绑定(bind)范围?

有人可以帮忙吗?

import AppDispatcher from '../appDispatcher.jsx';
import Events from 'events';
import axios from 'axios';

class FavoritesStore extends EventEmitter {
constructor(props) {
super(props);
//doesn't do the trick
this.updateState = this.updateState.bind(this);

this.state = {
importError: 'foo'
};

}


updateState() {
console.log('update state called');
// this line prints this.setState is undefined
this.setState('importError', 'is-active');
}

}

var favObj = new FavoritesStore();

AppDispatcher.register(function(payload) {
var action = payload.action;
switch (action.actionType) {
case 'UPDATE_ID':
favObj.updateState(action.data);
// this does not help it
// favObj.updateState(action.data).bind(this);

break;
}

return true;
});

export default favObj;

最佳答案

绑定(bind)没问题,但是 EventEmitter 是一个节点类,而不是 React 组件,因此它不维护状态或具有 setState 方法。

关于javascript - 在 ReactStore 方法中绑定(bind) Scope 以使用 setState(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46393940/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com