当usestate更新时,Map循环在usestate中的对象内部的数组中不工作Reactjs

jqjz2hbq  于 2021-09-13  发布在  Java
关注(0)|答案(2)|浏览(454)

当usestate更新时,Map循环在usestate中的对象内部的数组中不工作。Reactjs

import { useState } from "react";
import React from "react";

function Check() {

const [Children, setChildren] = useState({data:[], otherdata:{}});

 function handleChange(){
 Children["data"] = [...Children["data"], Children["data"].length]
 setChildren(Children)
 alert(Children["data"])
 }

  return (<React.Fragment>
    <div>Check</div>
    {Children["data"].map(data => <div>map</div>)}
    <button
     onClick={handleChange}
    >Add List</button>
  </React.Fragment>);
}

export default Check
jckbn6z7

jckbn6z71#

在本例中,要更新状态,必须使用状态设置器 setChildren 不要直接设置你的状态(不要这样做 Children["data"] = [...Children["data"], Children["data"].length] ).

9jyewag0

9jyewag02#

试试这个,我有固定的问题-

import { useState } from "react";
import React from "react";

function Check() {
  const [Children, setChildren] = useState({ data: [], otherdata: {} });

  function handleChange() {
    setChildren({
      ...Children,
      data: [...Children["data"], Children["data"].length],
    });
  }

  return (
    <React.Fragment>
      <div>Check</div>
      {Children.data.map((ele) => (
        <div>{ele}</div>
      ))}
      <button onClick={handleChange}>Add List</button>
    </React.Fragment>
  );
}

export default Check;

相关问题