我有一个列表,用户可以向其中添加项目。然后,用户可以“喜欢”列表中的任何项目,并且在该项目上显示喜欢的次数。但是,当我在某个项目上单击“喜欢”时,整个列表将消失。组件的状态具有所有正确的,更新的数据,因此我认为问题可能与组件渲染太早有关。状态更新后,如何确保组件(Category.jsx)重新正确显示?
App.js(父组件)
class App extends Component {
state = {
wentWell: [],
wellValue: '',
}
updateWellValue = e => this.setState({ wellValue: e.target.value });
wellSubmit = e => {
e.preventDefault();
this.setState({
wentWell: [...this.state.wentWell, {value: this.state.wellValue, likes: 0, dislikes: 0}],
wellValue: ''
})
}
wellUpvote = upvoteIndex => {
const wentWell = Object.assign({}, this.state.wentWell);
wentWell[upvoteIndex].likes += 1;
return this.setState({ wentWell });
}
render() {
return (
<>
<Title />
<div className="container">
<Category
name="Went Well"
items={this.state.wentWell}
inputValue={this.state.wellValue}
updateInput={this.updateWellValue}
submit={this.wellSubmit}
upvote={this.wellUpvote}
/>
</>
);
}
}
Category.jsx(子组件)
class Category extends Component {
state = {
items: this.props.items
}
static getDerivedStateFromProps(nextProps, prevState) {
if(nextProps.items !== prevState.items){
return ({ items: nextProps.items }) // <- this is setState equivalent
}
}
render() {
return (
<div className="category">
<h2>{this.props.name}</h2>
{/* ------ FORM (INPUT AND SUBMIT BUTTON) ------ */}
<form onSubmit={e => this.props.submit(e)}>
<input
placeholder="Enter note here"
value={this.props.inputValue}
onChange={e => this.props.updateInput(e)}
/>
<button type="submit" className={this.props.colorId}>Submit</button>
</form>
{/* ------ MAPPED OUT ITEMS ------ */}
{this.state.items.length > 0 ?
this.state.items.map((item, index) => {
return (<Item
key={`item-${index}`}
index={index}
upvote={this.props.upvote}
item={item}
/>);
}) : <h3>(Nothing here)</h3>
}
</div>
)
}
}
export default Category;
答案 0 :(得分:1)
好像您正在尝试在数组上使用Object.assign
。
const wentWell = Object.assign({}, this.state.wentWell);
尝试做
const tempWentWell = [...this.state.wentWell]