I have a list which users can add items to. The user can then 'like' any item in the list, and the number of likes is displayed on the item. When I click 'like' on an item, however, the entire list disappears. The component's state has all the correct, updated data, so I'm thinking the problem may be related to the component rendering too soon. How can I make sure the component (Category.jsx) re renders properly once the state is updated?
App.js (parent component)
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 (child component)
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;
Looks like you are trying to use Object.assign
on an array.
const wentWell = Object.assign({}, this.state.wentWell);
Try doing
const tempWentWell = [...this.state.wentWell]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.