简体   繁体   中英

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.

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.

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

Although when I console.log the state, it is correctly updated with the 2 dummy codes, the CreatableSelect still shows empty.

What I would like to understand is why the CreatableSelect does not rerender with the new 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 key={entry.id} isMulti onChange={handleChange} options={formatedCodes} value={tags} />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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