【问题标题】:Making the state of a component affect the rendering of a sibling when components are rendered iteratively迭代渲染组件时,使组件的状态影响同级组件的渲染
【发布时间】:2021-10-23 00:30:10
【问题描述】:

我有以下代码:

export default function Parent() {
    const children1 = someArrayWithSeveralElements.map(foo => <SomeView />);
    const children2 = someArrayWithSeveralElements.map(foo => <SomeCheckbox />);

    return (<>
        {children1}
        {/*Some other components*/}
        {children2}
    </>)
};

对于给定元素foo,有一个SomeView 组件,它根据SomeCheckbox 的状态有条件地呈现。我在想办法让复选框中的状态影响同级视图组件的呈现时遇到问题。

通常解决方案是在父组件中声明状态钩子并将它们传递给每个子组件,但由于兄弟姐妹是通过 foreach 循环呈现的,因此不可能这样做。

我目前的解决方案是也在循环中为每个foo 生成状态钩子,但这感觉有点笨拙,因为最好避免在循环内创建钩子(someArrayWithSeveralElements 不是毫无价值打算在安装后更改)。

有没有更优雅的方法来解决这个问题?

【问题讨论】:

    标签: reactjs react-hooks


    【解决方案1】:
    export default function Parent() {
        const [states, setStates] = React.useState([]);
        const children1 = someArrayWithSeveralElements.map((foo, i) => <SomeView state={states[i]} />);
        const children2 = someArrayWithSeveralElements.map((foo, i) => {
            const onStateChange = (state) => {
                setStates(oldStates => {
                    const newStates = [...(oldStates || [])]
                    newStates[i] = state;
                    return newStates;
                })
            }
            return <SomeCheckbox state={states[i]} onStateChange={onStateChange} />;
        });
    
        return (<>
            {children1}
            {/*Some other components*/}
            {children2}
        </>)
    };
    

    在父组件中使用状态。 注意:状态元素可以是undefined

    【讨论】:

      【解决方案2】:

      解决方案是你身边的,你需要在父组件中创建一个状态并将其传递给子组件。这适用于单个组件或一组组件,区别很简单:使用数组或对象作为状态。

      const [checkboxesStatus, setCheckboxesStatus] = useState({// fill initial data});
      
      const children1 = someArrayWithSeveralElements.map(foo =>
        <SomeView 
          visibile={checkBoxesStatus[foo.id]}
        />);
        
      const children2 = someArrayWithSeveralElements.map(foo =>
        <SomeCheckbox
          checked={checkBoxesStatus[foo.id]}
          onChange={// set new value to foo.id key}
        />)

      【讨论】:

        猜你喜欢
        • 2019-11-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-06-30
        • 2019-08-18
        • 2021-12-01
        • 1970-01-01
        相关资源
        最近更新 更多