【发布时间】:2021-09-13 19:30:38
【问题描述】:
好的,你们所有的 React Pros 都在那里。一段时间以来,我一直在努力解决这个问题。我有一个数据库,其中包含一个对象数组,其中嵌套了数组。
初始状态看起来像这样......
const initialState = [{
id: '',
mainContent:[
{
title: "",
content: []
},
],
sideContent:[
{
title: "",
content: []
},
],
pageTitle: ""
}]
对于一些内容,它类似于
const initialState = [{
id: '123',
mainContent:[
{
title: "About",
content: ['something', 'something else', 'other stuff', 'blah blah blah']
},
{
title: "Something else",
content: ['something', 'something else', 'other stuff', 'blah blah blah']
},
],
sideContent:[
{
title: "About",
content: ['something', 'something else', 'other stuff', 'blah blah blah']
},
{
title: "Something else",
content: ['something', 'something else', 'other stuff', 'blah blah blah']
},
],
pageTitle: "The main page title"
}]
我正在尝试创建一个表单,人们可以在其中使用 useReducer 编辑每个项目的内容。页面标题似乎与我的表单和 useReducer 配合得很好。但是,当我尝试映射主要内容以更新其任何数据时,我可以显示映射的数据,但似乎无法弄清楚如何编辑数据。
页面标题表单
<form className='form' onSubmit={onSubmit}>
<input
type='text'
placeholder='pageTitle'
value={state.pageTitle}
onChange={(e) =>
dispatch({
type: 'page-title',
fieldName: 'pageTitle',
payload: e.currentTarget.value,
})
}
/>
</form>
要显示的主要内容的映射
{state.mainContent.map((event,index) => (
<input
key={index}
type='text'
placeholder='main content'
value={event.title}
onChange={(e) =>
dispatch({
type: 'main-content',
fieldName: {} ,
payload: e.currentTarget.value,
})
}
/>
))}
reducer 代码...
function editReducer(state, action) {
switch (action.type) {
case 'page-title': {
return {
...state,
[action.fieldName]: action.payload,
};
}
case 'main-content': {
return {
...state,
mainContent: [{
...state.mainContent,
title: action.payload,
}]
};
}
case 'OnSuccess':
return {
setLoading: false,
pageTitle: action.payload.pageTitle,
mainContent: action.payload.mainContent,
sideContent: action.payload.sideContent,
error: ''
}
case 'OnFailure':
return {
loading: false,
error: 'Something went wrong'
}
default:
return state;
}
}
我发现,如果我将数组值硬编码到减速器中,我似乎可以编辑信息,但它只适用于硬编码的任何位置。
提前感谢您的所有帮助。
【问题讨论】:
标签: reactjs forms mapping use-reducer