我正在尝试通过在点击时使用material-ui获取文本字段中的值来更新我的状态。但是,似乎setState在这里更新todo状态总是落后一步。例如,如果我第一次输入'asdf',this.state.todo
为空(这是它初始化的内容)。然后我输入'1234'。点击后,我现在看到this.state.todo
是'asdf'!
问题1:我认为这可能与setState的“pending state transition”有关,但我不知道如何解决这个问题。
当我使用onChange和value使用vanilla(非material-ui)输入字段时,一切都运行良好。
问题2:所以我也很好奇为什么setState在material-ui getValue()情况下批处理过程,但是当我在输入中使用onChange / Value时却没有。
以下是这两个品种的代码。
Material-UI TextField:
const Main = React.createClass({
mixins: [ReactFire],
childContextTypes: {
muiTheme: React.PropTypes.object
},
getInitialState () {
return {
muiTheme: ThemeManager.getMuiTheme(LightRawTheme),
todo: ''
};
},
getChildContext() {
return {
muiTheme: this.state.muiTheme
};
},
componentWillMount() {
let newMuiTheme = ThemeManager.modifyRawThemePalette(this.state.muiTheme, {
accent1Color: Colors.deepOrange500
});
this.setState({muiTheme: newMuiTheme});
this.fb = new Firebase(rootUrl+'items/');
this.bindAsArray(this.fb,'items');
},
render() {
let containerStyle = {
textAlign: 'center',
paddingTop: '200px'
};
let standardActions = [
{ text: 'Okay' }
];
return (
<div>
<AppBar
title="Immaterial"
iconClassNameRight="muidocs-icon-navigation-expand-more" />
<div style={containerStyle}>
<TextField
hintText="Hint Text"
ref="newTodo"
/>
<Dialog
title="Go get 'em Tiger!"
actions={standardActions}
ref="superSecretPasswordDialog">
{this.state.todo}
</Dialog>
<h3>A journey of a thousand miles begins with a single step</h3>
<RaisedButton label="Carpe Diem" primary={true} onTouchTap={this._handleTouchTap} />
</div>
</div>
);
},
_handleTouchTap() {
var todo = this.refs.newTodo.getValue()
console.log(todo)
this.setState({todo: todo});
console.log(this.refs.newTodo.getValue())
console.log(this.state.todo)
// this.firebaseRefs.items.push({
// todo: this.state.todo
// });
//this.refs.superSecretPasswordDialog.show();
//this.refs.newTodo.clearValue();
}
香草输入
getInitialState: function() {
return {text: ''};
},
handleChange: function(event) {
//console.log(event.target.value)
this.setState({text: event.target.value})
},
handleButtonClick: function() {
//console.log(this.state.text)
this.props.itemsStore.push({
text: this.state.text,
done: false
});
this.setState({text:''});
},
render: function(){
return <div className="input-group">
<input
value = {this.state.text}
onChange = {this.handleChange}
type="text"
className = "form-control"
placeholder = "getting things done!"
/>
<span className="input-group-btn">
<button
onClick={this.handleButtonClick}
className="btn btn-default"
type="button">
Add
</button>
</span>
</div>
}