React/Redux的新手,我正在尝试让它成为一个用户可以拥有不同choice
和customAttribute
的尽可能多的choices
。
目前,我有一个他们可以创建UI的按钮,可以动态创建一个新的文本字段来输入另一个choice
和customAttribute
,但对于如何在redux中存储这样的东西,我完全感到困惑。
我已经看到了关于如何存储用户名和/或密码的其他问题和答案,但还没有看到任何关于如何存储包含我的完整状态的对象的示例。
我的组件
class CreateRIG extends Component<any, any> {
constructor(props) {
super(props);
this.state = {
rigName: '',
desc: '',
choices: [{
choice: '',
customAttribute: ''
}]
}
}
createUI() {
return this.state.choices.map((el, i) => (
<div key={i}>
<FormControl>
<Select
id="choice"
name="choice"
onChange={this.handleChange.bind(this, i)}
value={el.choice || ''}
>
<MenuItem value=''>
<em>None</em>
</MenuItem>
<MenuItem value='ID'>ID</MenuItem>
<MenuItem value='PSA'>PSA</MenuItem>
<MenuItem value='ExternalID'>ExternalID</MenuItem>
</Select>
</FormControl>
<div>
<TextField name="customAttribute" label="Attribute"
onChange={this.handleChange.bind(this, i)} value={el.customAttribute || ''} />
))
}
handleSubmit = (event) => {
event.preventDefault();
console.log(this.state);
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<div>
<TextField name="rigName"
value={this.state.rigName}
onChange={event => this.setState({ rigName: event.target.value })}/>
</div>
<div className={styles.spacing}>
<TextField name="description"
onChange={event => this.setState({ desc: event.target.value })}/>
</div>
{this.createUI()}
<Button type="submit"
onClick={this.props.onSubmitForm}>NEXT</Button>
</form>
);
}
}
const mapDispatchToProps = dispatch => {
return {
onSubmitForm: (rigName, desc, choice, customAttribute) => dispatch({ type: 'FORM_DATA'})
}
}
const connectedCreateRIGPage = connect(mapStateToProps, mapDispatchToProps)(CreateRIG);
export { connectedCreateRIGPage as CreateRIG };
export default CreateRIG;
操作.tsx
export const createRIGActions = {
searchInput
};
function searchInput(rigName, desc, choice, customAttribute) {
return {
type: createRIGConstants.STORE_FORM,
rigName,
desc,
choice,
customAttribute
}
}
Reducer.tsx
const initialState = {
results: []
};
export function createRIGReducer(state = initialState, action) {
switch (action.type) {
case createRIGConstants.STORE_FORM:
return {
...state,
results: state.results
}
// Need to somehow get the data from the form
default:
return state
}
}
如何在提交时将表单中的复杂对象存储到redux状态?现在我的onSubmit是控制台记录我想要的正确对象,所以这很好的
我相信传递给dispatch
的内容很重要。您也可以在那里添加payload
。
尝试以下操作:
const mapDispatchToProps = dispatch => {
return {
onSubmitForm: (rigName, desc, choice, customAttribute) => dispatch({ type: 'FORM_DATA', payload: {rigName, desc, choice, customAttribute}})
}
}
然后在你的减速器中,你可以访问payload
,如下所示:
export default (state=initialState, action) => {
switch(action.type) {
const { payload } = action;
case 'FORM_DATA':
return {
...state,
// here you can use data from payload to update the state
};
点击此处阅读Redux文档:管理规范化数据
我希望这能有所帮助!