當 東西像'SUBMIT_FORM'一樣發出時,做出XHR的動作是否合理?
絕對!操作不必返回像{ type: FOO }
這樣的對象,它們也可以返回函數,並且當您想要執行XHR內容時,這會使生活變得更輕鬆:http://redux.js.org/docs/advanced/AsyncActions.html。
至於你的問題的其他部分,如果你不遵循異步操作路徑,理論上ajax請求可以在任何地方都做到,但是在組件層次結構中有意義的最高中心點通常更好。在你的情況下,沒有理由讓WizardForm組件不應該處理這個問題。 WizardForm也有跟蹤的三個頁面中輸入的值,除非...
如果您已經使用終極版來存儲數據,那麼你是好去 - 只是消耗店,如果不您必須將一個函數從WizardForm傳遞到負責更新WizardForm本地狀態的每個單獨頁面。
在下面的僞示例中,您可以看到如何將SetPageValue上的函數傳遞給嚮導頁,並使用它來更改WizardForm的狀態。在您發佈的示例中,WizardForm從鏈中較高的位置獲取此函數,但原理相同,並且此概念對React很重要。
class WizardForm extends React.Component{
constructor(props){
super(props);
this.onHandleSubmit = this.onHandleSubmit.bind(this);
this.onSetPageValue = this.onSetPageValue.bind(this);
this.state = {
pageValues: {
1: '',
2: ''
}
}
}
onHandleSubmit() {
/* Do all xhr stuff, update state/store/whatever fits your application */
}
onSetPageValue(page, value){
this.setState({
pageValues: Object.assign({}, this.state.pageValues, {[page]:value})
});
}
render(){
return (
<div>
<WizardPage1 onSetPageValue={this.onSetPageValue}/>
<button onClick={this.onHandleSubmit}>Submit</button>
</div>
)
}
}
class WizardPage1 extends React.Component {
render(){
return (
<button onClick={() => {this.props.onSetPageValue(1, 'Foo!')}}>Trigger onSetPageValue</button>
);
}
}
你,先生,是天賜之物。 –
@ChadM哈哈,我不會那麼遠。 – dannyjolie
@dannyjolie在這種情況下你不會得到2個按鈕嗎? – softcode