首页 > 解决方案 > 无法使用附加元素访问更新的状态

问题描述

我正在使用按钮上的 onClick 创建 JSX 元素:

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

然后我更新状态(将新项目添加到数组):

//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,
          },
        ]);
    }

创建 JSX 元素后,我在该元素上有一个 onChange 事件:

注意:这个元素是用 onClick 创建的,现在我的状态中有两个对象。

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

但在这里我无法访问更新后的状态,我得到一个对象。

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

  };

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

标签: javascriptreactjsstate

解决方案


我会以不同的方式处理这个问题。您可以映射数据并以这种方式呈现组件,而不是将标记置于状态中:

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

以这种方式更容易跟踪您的状态。

沙盒示例


推荐阅读