Reactjs 为什么接收状态会在一瞬间消失?
我正试图从TestClass中分派actionC,以便Labelclass可以从reducer接收状态更改,如下所示 TestClassReactjs 为什么接收状态会在一瞬间消失?,reactjs,redux,reducers,Reactjs,Redux,Reducers,我正试图从TestClass中分派actionC,以便Labelclass可以从reducer接收状态更改,如下所示 TestClass class Test extends React.Component { constructor(props){ super(props) this.state = {text:props.text,onClick:props.onClick} this.onInput = this.onInput.bind(this)
class Test extends React.Component {
constructor(props){
super(props)
this.state = {text:props.text,onClick:props.onClick}
this.onInput = this.onInput.bind(this)
this.onSubmit = this.onSubmit.bind(this)
}
onInput(e){
this.setState({text:e.target.value})
}
onSubmit(e){
this.state.onClick(this.state.text)
}
render(){
return <div>
<form onSubmit={this.onSubmit}>
<input value={this.state.text} onChange={this.onInput} />
<button type="submit">Add Todo</button>
</form>
</div>
}
}
function mapDispatchToProps_Test(dispatch,ownProps){
return {onClick:(id)=>dispatch(actionC(id))}
}
Test.propTypes = {
text:PropTypes.string.isRequired,
onClick:PropTypes.func.isRequired
}
Test = connect(null,mapDispatchToProps_Test)(Test)
问题是,LabelClass render()的输出立即变得不可见
片刻后显示
我不想让它消失。原因是什么?您没有从您创建的减速机映射值
文本
,但您自己映射了减速机。在本例中,必须映射名为text
的减速机中的text
值:
function mapStateToProps_Label(state,ownProps){
// state.text is the state of your reducer
// state.text.text is one of the state value
return {
text:state.text.text
}
}
此外,据我所知,在标签中不需要状态:
class Label extends React.Component {
render(){
return <div> Hello<label>{this.props.text}</label></div>
}
}
我认为您应该在mapstatetops
中设置一个断点,以查看text
si在设置后是否被修改。您应该在减速机中放置一个断点,以查看某个操作是否发送了一个删除文本数据的操作。非常感谢!成功了。正如您所说,mapStatetoProps中的state.text是对reducer的引用。我可以通过更改reducer函数中的默认状态参数来确认它。正如你所说,我发送的内容毫无意义,因为根本没有映射。下次我会写一篇更有建设性的文章来证实你所说的。。。我的问题不在reducer中,但我忘记了e.preventDefault()。。。
function mapStateToProps_Label(state,ownProps){
// state.text is the state of your reducer
// state.text.text is one of the state value
return {
text:state.text.text
}
}
class Label extends React.Component {
render(){
return <div> Hello<label>{this.props.text}</label></div>
}
}
class Test extends React.Component {
constructor(props) {
super(props);
this.state = { text: props.text }
this.onInput = this.onInput.bind(this)
this.onSubmit = this.onSubmit.bind(this)
}
onInput(e) {
this.setState({ text: e.target.value });
}
onSubmit(e) {
this.props.onClick(this.state.text);
}
render() {
return <div>
<form onSubmit={this.onSubmit}>
<input value={this.state.text} onChange={this.onInput} />
<button type="submit">Add Todo</button>
</form>
</div>;
}
}