i'm trying to make a list when users selects their fav links onClick ...
Any idea why this doesn't work? it will push values to state.array in console.log but JSX will not render in ul.li
import React, { Component } from "react";
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
link: {
name: "",
type: "",
size: "",
tests: []
},
tests: ["1", "2", "3", "4"]
};
}
componentDidMount() {
console.log(this.state);
}
onClick = e => {
const linktests = this.state.link.tests;
console.log("clicked");
linktests.push(e.target.innerText);
console.log("link tests : " + linktests);
};
render() {
const { link, tests } = this.state;
const linktests = this.state.link.tests;
return (
<div>
<div id="link">
{linktests.map(stuff => (
<ul>
<li> {stuff} </li>
</ul>
))}
</div>
<br></br>
{tests.map(stuff => (
<ul>
<li onClick={this.onClick} value={stuff}>
{stuff}
</li>
</ul>
))}
</div>
);
}
}
hope someone can help :D <3 thanks
You need to set the new links to the state. Also use concat
or slice
on the original state array to avoid mutating it directly.
onClick = e => {
const linktests = this.state.link.tests.concat();
console.log("clicked");
linktests.push(e.target.innerText);
this.setState({link: { ...this.state.link, tests: linktests});
};
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.