簡體   English   中英

在 state 中存儲組件時,它的 props 更改時不再重新渲染?

[英]When storing a component in state, it no longer re-renders when its props are changed?

在一個特定的商業案例中,我有一系列以線性方式布置的組件,但是它們的順序可能會改變。 例如,我們有一個父組件:

export const Component = () => {

    const [data, setData] = useState(null);

    const [nextComponent, setNextComponent] = useState(null);

    return (
        //... component code here
        {nextComponent}
    );
}

Component代碼內部將是可以更改下一個組件的按鈕:

onClick={() => setNextComponent(<SomeComponent data={data} setData={setData} />)}

如果通過調用SomeComponent中的setData更改data ,則組件不會使用新的data屬性值重新渲染。

我知道這與存儲在SomeComponent中的 SomeComponent 有關,但無法理解為什么data不會在SomeComponent中更新 - 當然data只是指向 memory 位置的指針,因此應該在父級和子級之間具有相同的值?

這是因為僅當 function setNextComponent作為onClick回調的一部分被調用時,才會為SomeComponent更新data屬性。

執行此操作的“正確方法”是將對其父級的 state 重要的數據保存在SomeComponent中,然后將其作為該子級的條件渲染的一部分傳遞。

const ChildComponent = ({ data, setData }) => (
  <React.Fragment>
    <span>Current Data: {JSON.stringify(data)}</span>
    <input onChange={({target}) => setData(target.value)} placeholder="Enter New Data" />
  </React.Fragment>
);

const ParentComponent = () => {
  const CHILD_TYPES = { signIn: SomeComponent, signOut: OtherComponent };

  // keep track which component you want to be showing based on parent state
  const [activeComponentType, setActiveComponentType] = useState('signIn');

  // keep track of the data required for the child component(s)
  const [data, setData] = useState(null);

  // find and use the correct class for the current child type
  // (you could do this without an extra variable by using `React.createClass`)
  const ActiveComponentClass = CHILD_TYPES[activeComponentType];
  return (<ActiveComponentClass data={data} setData={setData} />);
}

此外,您應該考慮不要將組件存儲在 state 中。 這是不好的做法,通常不會按您期望的方式工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM