简体   繁体   中英

Data changes when coming back to it's component from another component

Hello (sorry for the title, I couldn't come up with anything else)!

I am using Redux to fetch my data:

componentDidMount() {
  this.props.fetchData('http://localhost:3001/locks')
}

// Stuff between
    const mapStateToProps = state => {
      return {
        doors: state.doors
      }
    }

And when I console.log console.log(doors) I see this: 在此处输入图片说明

Which is great! This is exacly how I want it to be, but if I navigate to ie /userstolock and then back to / (where I was before) I'm getting this error; TypeError: doors.map is not a function on this line:

const doors = this.props.doors.data || []
console.log(doors)
const doorsItems = doors.map(door => <DoorsItem door={door} />) // This line!!

Also my output change:

在此处输入图片说明

So I wonder why this problem occur. I'm sorry if I explained badly, but I don't understand this problem therefor I really can't explain it. If anyone need more code, please just let me know!

Thanks a lot.

Edit

I got a comment that suggested me to remove the .data . I tried it, but that gave me no luck. Here's the output from it: 在此处输入图片说明

I've been asked to add the reducer and here it is:

const initialState = {
  data: []
}

export function doorsHasErrored(state = false, action) {
  switch (action.type) {
    case 'DOORS_HAS_ERRORED':
      return action.hasErrored

    default:
      return state
  }
}

export function doorsIsLoading(state = false, action) {
  switch (action.type) {
    case 'DOORS_IS_LOADING':
      return action.isLoading

    default:
      return state
  }
}

export function doors(state = initialState, action) {
  switch (action.type) {
    case 'DOORS_FETCH_DATA_SUCCESS':
      return action.doors

    default:
      return state
  }
}

Update Sorry it's difficult to debug without full code, but it looks like your reducers might be overwriting your state.

Typically you'll modify the state object instead of setting it to the action, something like this:

export function doors(state = initialState, action) {
  switch (action.type) {
    case 'DOORS_FETCH_DATA_SUCCESS':
      return {
        ..state,
        doors: action.doors
      }

    default:
      return state
  }
}

I think when your other reducers are running, they may be overwriting the entire state. You may have to modify all your reducers to avoid overwriting.

Check out the redux reducer docs for typical reducer usage.

Object.assign({}, state, {doors: action.doors})

would be equivalent to

{
  ...state,
  doors: action.doors
}

--

Also it seems like your initial state might be missing doors ? Maybe something like:

const initialState = {
  doors: {
    data: []
  }
}

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