0
我想從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)
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入境
class Label extends React.Component {
constructor(props){
super(props)
this.state = {text:props.text}
}
render(){
return <div> Hello<label>{this.props.text}</label></div>
}
}
function mapStateToProps_Label(state,ownProps){
return {
text:state.text
}
}
Label = connect(mapStateToProps_Label)(Label)
Label.propTypes = {
text:PropTypes.string.isRequired
}
const App =() =>(
<div>
<Test text="" onSubmit onClick />
<Label text=""/>
</div>
)
ReactDOM.render(
<Provider store={store}><App /></Provider>,
document.getElementById('root')
);
行動和減速
const CDD_TODO = 'CDD_TODO'
const {PropTypes} = React;
const {createStore} = Redux;
const { Provider, connect } = ReactRedux;
let store = createStore(reducer)
//action
function actionC(text) {
console.log(CDD_TODO)
return { type: CDD_TODO, text:text }
}
function reducer(state = {}, action) {
switch (action.type) {
case CDD_TODO:
console.log("action",action.text)
return Object.assign({}, state, {
text:action.text
})
default:
return state
}
}
的特魯ble是來自LabelClass的輸出render()在瞬間顯示在之後變爲不可見 。
我希望它不會消失。原因是什麼?
非常感謝!它的工作。如你所說,mapStatetoProps中的state.text是reducer的引用。 我可以通過更改reducer函數中的默認狀態參數來確認它。 正如你所說,我派出的是毫無意義的,因爲根本沒有映射。 下次我會寫一點更有建設性的減速器來證實你的話。 ...我的問題不是在減速器,但我忘了e.preventDefault()... – user2255716