Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
507 views
in Technique[技术] by (71.8m points)

javascript - 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;
question from:https://stackoverflow.com/questions/66064102/react-parent-component-state-updates-but-child-does-not-re-render

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Alright, switching the CreatableSelect props from defaultValue to value apparently solved that issue!

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...