简体   繁体   中英

React userReducer init function not triggering on props update

I have a component which is a form which I use to create records in my database. I also want to be able to pass into this component values with which to populate the form, allowing me to then update my existing database records. Straightforward add/edit functionality from the same component.

The following code should explain how I am doing this. The media prop is an object containing the data. I have this data already in the parent element so setting the values here is fine and they pass thru without problem. However once the page is loaded the 3rd init argument of useReducer never re-triggers, and therefore my state cannot be overridden with the values passed down in the media prop. Is there a correct way to make the init function trigger when the props are updated, or is my issue architectural?

const MediaUploadForm = ({ media }) => {

  const init = (initialState) => {

    if (media) {
      // ... here I extract the values I need and override the initialState where required 
    } else {
      return initialState
    }
  }

  const [formState, dispatch] = useReducer(
    MediaFormReducer,
    initialState,
    init
  )

So using the new React hooks features and keeping the component functional allows me to use useEffects() This is similar to using a componentDidUpdate type event. So the following code allows me to check for the status of a prop ( media ) and then dispatch an action that sets my redux state.

useEffect(() => {
    if (media && id !== media.id) {
      dispatch(loadMedia(media))
    }

  })

Thanks to @sliptype for pointing me in the right direction

Copying props into state is considered an anti pattern in React. Props changes do not trigger reinitialising state, as you have seen.

This is described in https://reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html .

From the recap it looks like the current suggested solution matches

Alternative 1: To reset only certain state fields, watch for changes in a special property (eg props.userID).

This is an alternative, rather than the recommendation.

https://reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html#recap

Hope this link gives you more information around the topic, and the recommendations there help in future work.

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