[英]JSX component doesn't render map of state
当用户在点击时选择他们最喜欢的链接时,我正在尝试列出一个列表...
知道为什么这不起作用吗? 它会将值推送到 console.log 中的 state.array 但 JSX 不会在 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>
);
}
}
希望有人可以帮助:D <3 谢谢
您需要将新链接设置为状态。 还可以在原始状态数组上使用concat
或slice
以避免直接对其进行变异。
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});
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.