我使用componentWillReceiveProps
首次加载时,使用对象数组渲染表单以填充表单。表单正确呈现,没有错误。 this.state.data
呈现一组看起来像的对象:
this.state.data: (3) [Object, Object, Object]
[{
company: Company A,
title: Title A,
uniqueId: uniqueId A
},
{
company: Company A,
title: Title A,
uniqueId: uniqueId A
}]
当我在表单中输入handleInputChange
时,似乎导致每个键盘条目Uncaught TypeError: positions.map is not a function at PositionList StatelessComponent.ReactCompositeComponent.js.StatelessComponent.render
触发的错误,并且当我提交表单时this.state.data
似乎没有更改,因为它返回和看起来像的对象数组:
this.state.data: (3) [Object, Object, Object]
[{
company: Company A,
title: Title A,
uniqueId: uniqueId A
},
{
company: Company A,
title: Title A,
uniqueId: uniqueId A
},
{
"": "Whatever text I've typed in to the input field"
}]
请参阅下面的完整表格。虽然很长时间,但我认为我需要添加大量细节来说明问题。
function PositionItem(props) {
// Correct! There is no need to specify the key here:
return <li>
<input type="text" defaultValue={props.company} onChange={props.onChange} />
</li>;
}
function PositionList(props) {
const positions = props.positions;
const listPositions = positions.map((position) =>
// Correct! Key should be specified inside the array.
<PositionItem key={position.uniqueId.toString()}
company={position.company}
uniqueId={position.uniqueId}
onChange={props.onChange}
/>
);
return (
<ul>
{listPositions}
</ul>
);
}
export default class CareerHistoryFormPage extends Component {
constructor(props) {
super(props);
this.state = {
data: [],
};
this.handleFormSubmit = this.handleFormSubmit.bind(this);
this.handleInputChange = this.handleInputChange.bind(this);
}
componentWillReceiveProps(nextProps) {
const profileCandidateCollection = nextProps.profileCandidate;
const careerHistoryPositions = profileCandidateCollection && profileCandidateCollection.careerHistoryPositions;
const positions = careerHistoryPositions.map((position) =>
({
uniqueId: position.uniqueId || '',
company: position.company || '',
title: position.title || ''
}));
this.setState({
data: positions
})
}
handleInputChange(event) {
const target = event.target;
const value = target.type === 'checkbox' ? target.checked : target.value;
const name = target.name;
const data = {...this.state.data, ...{[name]: value}};
this.setState({
data: data
});
}
handleFormSubmit(event) {
event.preventDefault();
console.log("click", this.state.data);
}
render() {
console.log('this.state.data: ', this.state.data);
return (
<div>
<form className="careerHistoryForm" onSubmit={this.handleFormSubmit}>
<PositionList positions={this.state.data} onChange={this.handleInputChange} />
<input type="submit" className="btn btn-primary" value="Save" />
</form>
</div>
);
}
}
答案 0 :(得分:1)
您将数据设置为对象,然后尝试在其上调用.map
。
.map
仅适用于数组。
看起来你想要替换这一行:
const data = {...this.state.data, ...{[name]: value}};
这一行:
const data = [...this.state.data, {[name]: value}];