javascript - 如何在 React 中动态渲染数组
问题描述
我想动态渲染一个数组,其值将不断变化。
我有一个父组件
const Parent = () => {
const arr = [];
<Button onClick={()=>{
arr.push("some value")
}}
<Child data={arr}/>
}
export class Child extends React.Component {
return(
<h1>
{this.props.data}
</h1>
)
}
因此,最初页面将加载空白,只有一个按钮。我希望当单击按钮时,还应该显示 arr 值。但是,我看到即使在向数组添加值之后也不会显示任何值。
解决方案
像这样试试
const Parent = () => {
const [arr, setarr] = useState([]);
return (
<div>
<Button
onClick={() => {
setarr((oldArray) => [...oldArray, "some value"]);
}}
>
Button
</Button>
<Child data={arr} />
</div>
);
子组件
export class Child extends React.Component {
render() {
return <h1>{this.props.data}</h1>;
}
}
推荐阅读
- .net - dotnet 'new' 命令不适用于 Framework 4.5?
- jenkins - 评估 Jenkinsfile 中的变量 - 单引号内的单引号
- docker - 将 ftp 目录挂载到 docker 容器
- javascript - 模拟和资产来自外部库的函数
- javascript - JavaScript 如何将字符串转换为函数
- java - 使用分配的计时器限制重新启动 systemd 服务
- spring-boot - Spring Boot JPA - OneToMany 关系和数据库结构
- php - 在用户共享日历上添加事件
- java - 为什么得到 Gson MalFormatException
- r - 将列添加到数据框中,其顺序取决于其他列