Connect search bar and search results components to global state

后端 未结 2 547
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-24 08:16

I am new to ReactJS and I recently came up with this redux date store that react uses mostly. I am trying to have a good grasp on it.

Just for the understanding purpose,

2条回答
  •  梦谈多话
    2021-01-24 08:50

    1. You should change your store display function which always record to origin data

    Maybe you can change this to see store change:

    function getState() {
      console.log(store.getState());
    }
    

    Just console.log(initialState.jsonData); always show the origin data.

    2. reducer function always need to change the current state

    function reducer(state = initialState, action) {
      console.log('reducer', state, action); 
    
      switch(action.type) {
        case 'SEARCH':      
          const updatedPattern =  new RegExp(action.payload.pattern)
          return {
            jsonData: state.jsonData.filter(item => updatedPattern.test(item.state))
          };
    
        default:
          return state;
      }
    }
    

    The key change is after: jsonData: state.jsonData.filter(item => updatedPattern.test(item.state))

    3. Maybe you can use store.subscribe(handleChange) to get store change

    const unsubscribe = store.subscribe(getState)
    

    use the store.subscribe to auto get state change action like react-redux does.

提交回复
热议问题