我正在尝试更新存储在深层嵌套对象中的值。它包含许多信息并且模式是固定的。我正在尝试复制对象,然后从输入返回具有更新值 onChange 的对象。但是,我无法成功正确复制完整树并返回更新的内容。
DEMO: https://codesandbox.io/s/4j7x8jlk9w
该对象看起来像:
content: {
label: "Label",
templates: [
{
name: "example",
type: "the type",
items: [
{
key: "key1",
properties: {
text: {
label: "The Label 1",
value: "The Value 1"
},
color: {
label: "Color",
value: "#123"
}
}
},
{
key: "key2",
properties: {
text: {
label: "The Label 2",
value: "The Value 2"
},
color: {
label: "Color",
value: "#456"
}
}
}
]
}
]
}
减速机:
case "UPDATE_VALUE":
const content = state.content.templates[state.templateKey].items[
state.itemKey
].properties.text.value =
action.value;
return { ...state, content };
default:
return state;
}
组件:
import React, { PureComponent } from "react";
import { connect } from "react-redux";
import { updateValue } from "./actions";
class Page extends PureComponent {
render() {
const { content, templateKey, itemKey } = this.props;
return (
<div>
<h1
style={{
color:
content.templates[templateKey].items[itemKey].properties.color
.value
}}
>
{content.templates[templateKey].items[itemKey].properties.text.value}
</h1>
<input
name={content.templates[templateKey].items[itemKey].key}
value={
content.templates[templateKey].items[itemKey].properties.text.value
}
onChange={e => this.props.updateValue(e.target.name, e.target.value)}
/>
</div>
);
}
}
const mapStateToProps = state => ({
content: state.content,
templateKey: state.templateKey,
itemKey: state.itemKey
});
const mapDispatchToProps = dispatch => ({
updateValue: (key, value) => dispatch(updateValue(key, value))
});
export default connect(
mapStateToProps,
mapDispatchToProps
)(Page);