gpt4 book ai didi

javascript - React Js,this.context 在构造函数方法中未定义

转载 作者:行者123 更新时间:2023-11-29 10:11:37 25 4
gpt4 key购买 nike

我实际上正在尝试开发一个简单的组件,该组件对应于一个列表,当我按下一个按钮时,我会再填充一个项目。

我的问题是我使用 ES6,所以我不使用 getInitialState,我使用构造函数进行初始化,如文档中所述。

我的问题是,现在 this.context 在我的构造函数中未定义,我无法直接在构造函数中获取我的第一次数组(或预加载数组):

import React from 'react';
import ListStore from '../stores/ListStore';

class Client extends React.Component {


constructor(props){
super(props);
this.state = this.getStoreState(); // throw me that in getStoreState, this.context is undefined
}


static contextTypes = {
executeAction: React.PropTypes.func.isRequired,
getStore: React.PropTypes.func.isRequired
};

componentDidMount() {
this.context.getStore(ListStore).addChangeListener(this._onStoreChange.bind(this));
}

componentWillUnmount() {
this.context.getStore(ListStore).removeChangeListener(this._onStoreChange.bind(this));
}

_onStoreChange () {
this.setState(this.getStoreState());
}

getStoreState() {
return {
myListView: this.context.getStore(ListStore).getItems() // gives undefined
}
}


add(e){
this.context.executeAction(function (actionContext, payload, done) {
actionContext.dispatch('ADD_ITEM', {name:'toto', time:new Date().getTime()});
});
}

render() {
return (
<div>
<h2>Client</h2>
<p>List of all the clients</p>
<button onClick={this.add.bind(this)}>Click Me</button>
<ul>
{this.state.myListView.map(function(test) {
return <li key={test.time}>{test.name}</li>;
})}
</ul>
</div>
);
}
}


export default Client;

我只想在构造函数中预加载数组,无论它是否为空,这正是我的商店返回的内容:

从'fluxible/addons/BaseStore'导入BaseStore;

class ListStore extends BaseStore {

constructor(dispatcher) {
super(dispatcher);
this.listOfClient = [];
}

dehydrate() {
return {
listOfClient: this.listOfClient
};
}

rehydrate(state) {
this.listOfClient = state.listOfClient;
}


addItem(item){
this.listOfClient.push(item);
this.emitChange();
}

getItems(){
return this.listOfClient;
}

}

ListStore.storeName = 'ListStore';
ListStore.handlers = {
'ADD_ITEM': 'addItem'
};

export default ListStore;

谢谢你的帮助

最佳答案

你面临的问题是因为你的组件应该是无状态的,我不能这么说,状态应该存在于你的商店中,(UI 状态,“可以”存在于你的组件中,但这是值得商榷的)

您应该做的是使用更高级别的组件,将您的 React 组件包装在更高级别的组件中,让该组件从商店中获取状态,并将其作为 props 传递给您的组件。

这样您就不需要初始状态,您只需设置 defaultProps 和 propTypes。

这样你的组件是无状态的,你可以充分利用 react 生命周期,它也变得可重用,因为你没有在你的组件中获取实际数据的逻辑。

好读

希望这有帮助:)

关于javascript - React Js,this.context 在构造函数方法中未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32382975/

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