react-redux change in state, not re-render the page

 

1. Problem?

在redux中,通过reducer来对state的进行更新,但是我在reducer中改变了state的值,但是页面没有重新渲染,并且在控制台输出显示state的值已经改变

Code:

const initStore = [
    {
        name: 'lili',
        blogTitle: 'nihao',
        blogContent: 'nihao',
        nowTime: '2016-4-10'
    },
    {
        name: 'bob',
        blogTitle: '你好!',
        blogContent: '你好!',
        nowTime: '2016-5-15'
    }
];
export default function (state = initStore, action) {
    switch (action.type) {
        case 'DELETE':
            state.splice(action.index,1);
            console.log('state:',state);//输出state的值已经改变
            return state;
    }
}

2. reasons

reducer 就是一个纯函数,接收旧的 state 和 action,返回新的 state。保持 reducer 纯净非常重要。

Never do these operations in the reducer inside:

修改传入参数;
执行有副作用的操作,如 API 请求和路由跳转;
调用非纯函数,如 Date.now() 或 Math.random()。

Store will pass two parameters reducer: current state and Action , so you can not directly modify the value of the state, redux will compare the old and new state, will lead directly modify the state also changed the interior of the store, then there will be no change in the old and new state . Page will not re-rendering.

3. Solution

  • Do not modify the State . Use Object.assign()built a copy.

example

function todoApp(state = initialState, action) {
  switch (action.type) {
    case SET_VISIBILITY_FILTER:
      return Object.assign({}, state, {
        visibilityFilter: action.filter
      })
    default:
      return state
  }
}

 

Guess you like

Origin blog.csdn.net/qq_36742720/article/details/90449033