首页 > 解决方案 > 如何在 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 值。但是,我看到即使在向数组添加值之后也不会显示任何值。

标签: javascriptreactjs

解决方案


像这样试试

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>;
  }
}

推荐阅读