react 方法未定义_javascript-React.js,this.context在构造方法中未定义

我实际上是在尝试开发一个与列表相对应的简单组件,当我按下按钮时,我会再填写一个项目.

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

我的问题是,现在,在构造函数中未定义this.context,并且无法直接在consntructor内部获取我的第一个时间数组(或预加载的数组):

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 (

Client

List of all the clients

Click Me

{this.state.myListView.map(function(test) {

return

{test.name};

})}

);

}

}

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组件包装在一个更高级别的组件中,让该组件从商店中获取状态,并将其作为道具传递给您的组件.

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

这样,您的组件是无状态的,并且您可以充分利用react生命周期,并且还可以重用,因为您没有在组件中获取实际数据的逻辑.

好读

希望这可以帮助 :)

标签:reactjs,flux,fluxible,javascript

来源: https://codeday.me/bug/20191027/1948336.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值