简体   繁体   English

反应父组件 state 更新但子不重新渲染

[英]React parent component state updates but child does not re-render

I have a react app with many entries, each entry can have many tags.我有一个包含许多条目的反应应用程序,每个条目可以有很多标签。

It is a moderation app, so the entries are listed on a page and a user can click on an entry to moderate it (for example, to add or remove tags).它是一个审核应用程序,因此条目会列在页面上,用户可以单击条目进行审核(例如,添加或删除标签)。 Once clicked, the entry will show up in a modal.单击后,该条目将显示在模式中。

Once the modal is open, a user can chain the entries with a 'next' button, so that the modal does not close.一旦模式打开,用户可以使用“下一步”按钮链接条目,这样模式就不会关闭。 When the user clicks 'next', the next entry gets loaded into the modal.当用户单击“下一步”时,下一个条目将加载到模式中。

In the modal, I have a react CreatableSelect component that takes the tag list of that loaded entry.在模式中,我有一个反应 CreatableSelect 组件,它采用该加载条目的标记列表。

The issue is that when the user clicks 'next', the tags in the CreatableSelect don't update, it is still showing the tags of the first loaded entry.问题是当用户单击“下一步”时,CreatableSelect 中的标签不会更新,它仍然显示第一个加载条目的标签。

Here is the code, transformed to make my issue hopefully clearer.这是代码,经过转换以使我的问题更清楚。

  1. first, the component is loaded with an empty array of codes首先,组件加载了一个空的代码数组
  2. second, the useEffect is triggered and populates the state with 2 dummy codes其次,触发 useEffect 并使用 2 个虚拟代码填充 state

Although when I console.log the state, it is correctly updated with the 2 dummy codes, the CreatableSelect still shows empty.虽然当我控制台记录 state 时,它已正确更新为 2 个虚拟代码,但 CreatableSelect 仍然显示为空。

What I would like to understand is why the CreatableSelect does not rerender with the new state?我想了解的是为什么 CreatableSelect 不使用新的 state 重新渲染?

Thank you!谢谢!

const SelectTags = ({ nextEntry, entry, topicId, updateEntry }) => {

  const projectCodes = useSelector(state => state.project.codes);
  const formatedCodes = projectCodes.map(code => ({value: code, label: code, isFixed: true}) );
  const [selectedTags, setSelectedTags] = useState([]);

  useEffect(() => {
    const newTags = [{value: 'hello', label: 'hello'}, {value: 'world', label: 'world'}];
    setSelectedTags([...newTags]);
  }, [entry]);

  const handleChange = newValue => setSelectedTags([...newValue]);

  const setSubmittingFalse = () => setSubmitting(false);

  return (
    <CreatableSelect isMulti onChange={handleChange} options={formatedCodes} defaultValue={selectedTags} />
  )
};

export default SelectTags;

Alright, switching the CreatableSelect props from defaultValue to value apparently solved that issue!好吧,将 CreatableSelect 道具从 defaultValue 切换到 value 显然解决了这个问题!

<CreatableSelect key={entry.id} isMulti onChange={handleChange} options={formatedCodes} value={tags} />

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

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