gpt4 book ai didi

javascript - 使用动态创建的 react 组件并填充状态值

转载 作者:行者123 更新时间:2023-11-29 22:48:28 25 4
gpt4 key购买 nike

下面是概念笔的证明。我正在尝试显示很多 的输入字段,并尝试在一个大对象中更改时收集他们的输入。如您所见,输入不会改变它们的值,这是我所期望的,因为它们是使用 useEffect() 创建一次并在那个实例中填充的。

我认为解决这个问题的唯一方法是在 values 更改时使用 React.cloneElement 并将新值注入(inject)克隆元素。这就是为什么我在这支笔中创建了 2000 个元素,这将是一个主要的性能消耗,因为当状态改变时每个元素都会重新渲染。我尝试使用 React.memo 仅使具有更改值的输入重新呈现,但我认为 cloneElement 无论如何都会重新呈现它,这听起来应该是因为它是克隆的。

如何在此设置中实现单个字段的高性能更新?

https://codepen.io/10uur/pen/LYPrZdg

编辑:使用我之前提到的 cloneElement 解决方案的工作笔,明显的性能问题和所有输入重新呈现。

https://codepen.io/10uur/pen/OJLEJqM

最佳答案

这是实现所需行为的一种方法: https://codesandbox.io/s/elastic-glade-73ivx

一些提示:

  1. 我不建议将 React 元素置于状态中,而更喜欢将纯数据(数组、对象等)置于将在 return/render 方法中映射到 React 元素的状态中。
  2. 在渲染元素数组时不要忘记使用 key 属性
  3. 使用 React.memo 避免在 props 相同时重新渲染组件
  4. 使用 React.useCallback 来内存回调(这将有助于对 child 使用 React.memo)
  5. 使用状态 setter 的函数形式访问旧状态并更新它(这在使用 React.useCallback 时也有帮助,避免在状态更改时重新创建回调)

完整代码如下:

import React, { useEffect } from "react";
import ReactDOM from "react-dom";

import "./styles.css";

const INPUTS_COUNT = 2000;

const getInitialState = () => {
const state = [];
for (var i = 0; i < INPUTS_COUNT; i++) {
// Only put plain data in the state
state.push({
value: Math.random(),
id: "valueContainer" + i
});
}

return state;
};

const Root = () => {
const [state, setState] = React.useState([]);

useEffect(() => {
setState(getInitialState());
}, []);

// Use React.useCallback to memoize the onChangeValue callback, notice the empty array as second parameter
const onChangeValue = React.useCallback((id, value) => {
// Use the functional form of the state setter, to update the old state
// if we don't use the functional form, we will be forced to put [state] in the second parameter of React.useCallback
// in that case React.useCallback will not be very useful, because it will recreate the callback whenever the state changes
setState(state => {
return state.map(item => {
if (item.id === id) {
return { ...item, value };
}
return item;
});
});
}, []);

return (
<>
{state.map(({ id, value }) => {
// Use a key for performance boost
return (
<ValueContainer
id={id}
key={id}
onChangeValue={onChangeValue}
value={value}
/>
);
})}
</>
);
};

// Use React.memo to avoid re-rendering the component when the props are the same
const ValueContainer = React.memo(({ id, onChangeValue, value }) => {
const onChange = e => {
onChangeValue(id, e.target.value);
};

return (
<>
<br />
Rerendered: {Math.random()}
<br />
<input type="text" value={value} onChange={onChange} />
<br />
</>
);
});

ReactDOM.render(<Root />, document.getElementById("root"));

关于javascript - 使用动态创建的 react 组件并填充状态值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57912426/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com