简体   繁体   English

无法使用附加元素访问更新的 state

[英]can't access to updated state with appanded element

I'm creating JSX element with the onClick on the button:我正在使用按钮上的 onClick 创建 JSX 元素:

      <div onClick={() => addWeek()} >
        add week
      </div>

then I update state (add new items to array):然后我更新 state (将新项目添加到数组):

//my state that has one object initially (I want to add more)
  const [weekly, setweekly] = useState([
    {
      id: 'n1',
      day_week: null,
      start_time: null,
      end_time: null,
    },
  ]);
    const addWeek = () => {
        setweekly([
          ...weekly,
          {
            id: `n${weekly.length + 1}`,
            day_week: null,
            start_time: null,
            end_time: null,
          },
        ]);
    }

after I create JSX element I have an onChange event on that element:创建 JSX 元素后,我在该元素上有一个 onChange 事件:

NOTE: This element created with onClick and I have two objects inside my state now.注意:这个元素是用 onClick 创建的,我的 state 现在有两个对象。

       <select
            onChange={(event) => handleWeekly(event)}
            id={`n${weekly.length + 1}`}
          >
//Some options
         </select>

but in here I can't access the updated state I get one object.但在这里我无法访问更新的 state 我得到了一个 object。

  const handleWeekly = (event) => {
   // I get one object
    console.log(weekly);

  };

CODE SAND BOX: https://codesandbox.io/s/strange-nightingale-l6qg3?file=/src/App.js:0-1372代码沙盒: https://codesandbox.io/s/strange-nightingale-l6qg3?file=/src/App.js:0-1372

I would approach this problem differently.我会以不同的方式处理这个问题。 Instead of putting markup in the state you can map through your data and render your components this way:而不是在 state 中放置标记,您可以通过您的数据 map 并以这种方式呈现您的组件:

export default function App() {
  const [weeks, setWeek] = useState([
    {
      id: "n1",
      day_week: null,
      start_time: null,
      end_time: null
    }
  ]);
  const addWeek = () => {
    setWeek([
      ...weeks,
      {
        id: `n${weeks.length + 1}`,
        day_week: null,
        start_time: null,
        end_time: null
      }
    ]);
  };

  const handleWeekly = (event) => {
    console.log(weeks);
  };

  return (
    <div className="App">
      <div onClick={() => addWeek()}>add week</div>
      {weeks.map((week) => {
        return (
          <select
            onChange={(event) => handleWeekly(event)}
            id={`n${week.id}`}
            key={`n${week.id}`}
          >
            <option value="volvo">Volvo</option>
            <option value="saab">Saab</option>
            <option value="mercedes">Mercedes</option>
            <option value="audi">Audi</option>
          </select>
        );
      })}
    </div>
  );
}

It's easier to keep track of your state this way.以这种方式更容易跟踪您的 state。

Sandbox Example 沙盒示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM