我是react.js和flux体系结构的新手。我刚刚创建了一个非常小的例子来理解通量架构的流程。但是在添加动作和存储后我面临一些问题。这是我的代码:
Name.jsx(组件)
var React = require('react');
var ReactDOM = require('react-dom');
var NameActions = require('../actions/NameActions');
var NameStore = require('../stores/NameStore');
var Name = React.createClass({
getInitialState: function() {
return {fname: 'Arjita', lname: 'Mitra'};
},
_changeIt: function() {
var fName = this.state.fname;
var lName = this.state.lname;
var data = {fName: fName , lName: lName};
NameActions.setName(data);
},
handleChange: function(field,e) {
var nextState = {}
nextState[field] = e.target.value;
this.setState(nextState);
},
render: function() {
return (
<div>
<div className = "container">
<input type="text" name="firstName" id="idFname" value={this.state.fname}
onChange={this.handleChange.bind(this,'fname')}/>
<input type="text" name="lastname" id="idLname" value={this.state.lname} onChange={this.handleChange.bind(this, 'lname')}/>
<button type="button" name="btnok" onClick={this._changeIt()}>Process</button>
</div>
</div>
);
}
});
module.exports = Name;
NameActions.js
var ActionsHelper = require('./ActionsHelper');
var NameConstants = require('../constants/NameConstants');
var NameActions = {
setName: function(value) {
ActionsHelper.dispatch(NameConstants.SET_NAME, value);
}
}
module.exports = NameActions;
NameConstants.js
var _BASE = "NAME_CONSTANTS";
function construct(value) {
return _BASE + "_" + value;
}
module.exports = {
SET_NAME : construct("SET_NAME")
};
NameStore.js
var AppDispatcher = require('../dispatcher/AppDispatcher');
var EventEmitter = require('events').EventEmitter;
var _ = require('underscore');
var NameConstants = require('../constants/NameConstants');
function setValue(value) {
console.log(value);
}
var NameStore = _.extend({}, EventEmitter.prototype, {
addChangeListener : function(callback) {
this.on('change', callback);
},
emitChange : function() {
this.emit('change');
},
removeChangeListener : function(callback) {
this.removeListener('change', callback);
}
});
AppDispatcher.register(function(payload) {
var action = payload.action;
var data = action.data;
switch (action.actionType) {
case NameConstants.SET_NAME :
setValue(data.value);
break;
default :
return true;
}
NameStore.emitChange();
return true;
});
module.exports = NameStore;
我目前面临的错误是,一旦我开始在名字字段中输入其投掷警告 -
警告:setState(...):在现有状态转换期间(例如render
内)无法更新。渲染方法应该是道具和状态的纯函数。
http://localhost:8080/js/bundle.js
第24836行
另一个错误是无法在调度中间发送。
我被困了很长时间。请帮我解决。
答案 0 :(得分:0)
问题在于这一行:
<button type="button" name="btnok" onClick={this._changeIt()}>Process</button>
当你想要传递对它的引用时,你在渲染中调用this._changeIt。您可以通过将其更改为以下内容来解决此问题:
<button type="button" name="btnok" onClick={this._changeIt.bind(this)}>Process</button>