简体   繁体   English

在 React 动态创建的元素中更改 state

[英]Change state in a dynamically created element in React

Let's say I have this component code:假设我有这个组件代码:

import * as React from 'react'

export default function App() {
  const [value, setValue] = React.useState('default');
  const defaultPanes = new Array(1).fill(null).map((_, index) => {
    const id = String(index + 1);
    return {
      label: `Some label`,
      children: (
        <div>
          Child {id}, value: {value}
        </div>
      ),
      key: id,
    };
  });
  const [items, setItems] = React.useState(defaultPanes);
  console.log(items, value);

  return (
    <div>
      <h1>{items[0].label}</h1>
      <div>{items[0].children}</div>
      <p onClick={() => setValue('new value')}>Klick me</p>
    </div>
  );
}

How can I change the state {value} in this dynamically rendered element "defaultPanes"?如何更改此动态呈现的元素“defaultPanes”中的 state {值}?

Link to this code in Stackblitz在 Stackblitz 中链接到此代码

Your items array shouldn't be a state value, and instead, you should just use defaultPanes /a regular variable.您的items数组不应该是 state 值,相反,您应该只使用defaultPanes /一个常规变量。 JSX shouldn't be part of state exactly for the reason you've shown. JSX 不应该是 state 的一部分,正是因为你所展示的原因。 State values only update when they're explicitly told to update via the state setter function ( setItems in your case) and not when values used within the state change. State 值仅在明确告知通过 state setter setItems (在您的情况下为 setItems )进行更新时更新,而不是在 state 中使用的值更改时更新。 If you find that you have state that relies on other state values or props, aren't using the state setter function, or are including JSX in your state, then you should think about whether your state should really be a state value.如果您发现自己有state,它依赖于其他882744437401188值或道具,则不使用8827444437401188 SETETER function,或者在8827444401188,您是否应该在882744401188中包括8888,您是否应该在882744488中进行。 Instead, I would suggest using useMemo() to create your items array when value changes:相反,我建议在value更改时使用useMemo()创建items数组:

 function App() { const [value, setValue] = React.useState('default'); const items = React.useMemo(() => new Array(1).fill(null).map((_, index) => { const id = String(index + 1); return { label: `Some label`, children: ( <div> Child {id}, value: {value} </div> ), key: id, }; }), [value]); return ( <div> <h1>{items[0].label}</h1> <div>{items[0].children}</div> <p onClick={() => setValue('new value')}>Click me</p> </div> ); } ReactDOM.createRoot(document.body).render(<App />);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.production.min.js"></script>

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

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