简体   繁体   English

如何为反应元素的多个副本创建独立状态?

[英]How do I create independent states for multiple copies of a react element?

New to React. React 新手。

I am trying to create a set of 12 range sliders, in two columns of six.我正在尝试在两列六中创建一组 12 个范围滑块。 Each column is declared separately and each column independently declares the instance of the slider.每列单独声明,每列独立声明 slider 的实例。 Each range slider uses the package react-slider and has a currentValue state that is passed down as a prop along with the setCurrentValue method as the setState .每个范围 slider 使用 package react-slider 并具有一个currentValue state 作为 prop 以及setCurrentValue方法作为setState传递下来。

My issue is that when I display the values below each slider, they all sync up together, ie.我的问题是,当我在每个 slider 下方显示值时,它们都同步在一起,即。 they appear to all use the same variable.他们似乎都使用相同的变量。 How do I get React to differentiate between each 'instance' as such?我如何让 React 区分每个“实例”? SliderValueText just returns an element with the value displayed. SliderValueText只返回一个显示值的元素。

The production value is a boolean that just tweaks the title slightly. production价值是 boolean,只是稍微调整了标题。 The Slider element: Slider元件:

// imports here    
export const Slider = (props) => {
    const { currentValue, setCurrentValue, title, production } = props
    
    return (
        <>
            <ReactSlider
                className='customSlider'
                key={title+production}
                thumbClassName='customSlider-thumb'
                trackClassName='customSlider-track'
                markClassName='customSlider-mark'
                min={0}
                max={100}
                defaultValue={0}
                value={currentValue}
                onChange={(value) => setCurrentValue(value)}
            />
            <br/>
            <SliderValueText currentValue={currentValue} />
        </>
    )
}

The SliderSet element: SliderSet元素:


    // imports
    export const SliderSet = (props) => {
        const { currentValue, setCurrentValue, production } = props
    
        return (
            <>
                <Slider
                    currentValue={currentValue}
                    setCurrentValue={setCurrentValue}
                    title='Lorem Ipsum'
                    production={production}
                />
                // 5 further slider declarations here, all identical but with different titles
            </>
        

       )
    }

I have tried using the key prop and a map (below) and I have tried using an array as the currentValue state declaration in the App.js file but I cannot figure out how to use setCurrentValue with an array (below but further).我尝试使用key prop 和 map(下),我尝试使用数组作为 App.js 文件中的currentValue state 声明,但我不知道如何将setCurrentValue与数组一起使用(下但进一步)。

In this instance, titles is an array of all of the titles for each individual slider.在这种情况下,titles 是每个 slider 的所有标题的数组。


    const num = 6
    const nums = new Array(num)
    const element = [...nums.keys()].map(i => <Slider 
        key={i+titles[i]+production}
        usableKey={i}
        title={titles[i]}
        production={production}
        setCurrentValue={setCurrentValue} 
        currentValue={currentValue}
    />)
    
    return (
        <div>{element}</div>

State Array State 阵列

// App.js
const [currentValue, setCurrentValue] = useState([0, 0, 0, 0, 0, 0])

// No idea how the usage for this works

Any and all help is appreciated:)任何和所有的帮助表示赞赏:)

You need to pass different values to each slider, and different functions to update that state.您需要将不同的值传递给每个 slider,并使用不同的函数来更新 state。

Many ways to go about it. go 关于它的许多方法。 Here is one example.这是一个例子。

export const App = () => {
  const [sliderValue, setSliderValue] = useState(Array(12).fill(0));

  return sliderValue.map((val, index) => (
    <Slider
      currentValue={val}
      setCurrentValue={(newVal) => {
        const newSliderValues = [...sliderValue];
        newSliderValues[index] = newVal;
        setSliderValue(newSliderValues);
      }}
    />
  ));
};

When the state is an object (like this array) the internals of react determines if the object has updated by doing what's called a shallow comparison.当 state 是 object (如这个数组)时,react 的内部确定 object 是否通过执行所谓的浅比较更新。 It just checks if it's the same object or not, it doesn't examine the actual content of the object.它只是检查它是否相同 object,它不检查 object 的实际内容。

For that reason, when updating the array of slider values we first make a shallow copy of the array.因此,在更新 slider 值的数组时,我们首先制作数组的浅表副本。 Then update that shallow copy and finally set the state of the new array.然后更新那个浅拷贝,最后设置新数组的 state。

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

相关问题 当同一个 DatePicker 组件在列表中迭代多次时,如何使 React Datepicker 状态独立? - How do i make React Datepicker states independent when the same DatePicker component is iterated many in a list? 如何使用 typescript 从 React 中的状态创建新的 object? - How do I create a new object from states in React with typescript? 如何在React中基于多个状态禁用按钮? - How do I disable a button based on multiple states in React? 两个独立的React副本 - Two independent copies of React 如何在状态中使用切换? - How do I use toggle in react with states? 如何在 React 中正确更改 2 个状态? - How do I change 2 states properly in React? React - 如何根据道具更改多个初始状态 - React - How can I change multiple initial states based on the props 错误UncaughtReactDOM.render():无效的组件元素。 这可能是由于意外加载React的两个独立副本引起的 - Error UncaughtReactDOM.render(): Invalid component element. This may be caused by unintentionally loading two independent copies of React 如何有条件地计算本机反应中的状态之一? - How do I conditionally count one of the states in react native? 如何在 React Hooks 中更新 object 数组中的状态 `onChange` - How do I update states `onChange` in an array of object in React Hooks
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM