0

我试图理解这个 React redux 示例:https ://codesandbox.io/s/f2ded

reducer.js中,初始状态是:

const initialState = {
  taskName: "",
  tasks: []
};

App.js中,我们有:

const mapStateToProps = state => {
  return {
    ...state.list
  };
};

state没有属性,liststate.list应该是一个空对象{}。但是,它实际上成立

感谢任何帮助理解它是如何工作的。谢谢你。

4

2 回答 2

2

这是因为底部的 combineReducers

const reds = combineReducers({ list });

export default reds;

这意味着 Redux 状态的那部分中的所有内容都是state.list.taskNamestate.list.tasks等等。

[编辑] 只是想从官方文档中添加一些清晰度,https://redux.js.org/api/combinereducers/

rootReducer = combineReducers({potato: potatoReducer, tomato: tomatoReducer})
// This would produce the following state object
{
  potato: {
    // ... potatoes, and other state managed by the potatoReducer ...
  },
  tomato: {
    // ... tomatoes, and other state managed by the tomatoReducer, maybe some nice sauce? ...
  }
}
于 2020-02-18T12:48:15.133 回答
0

要更深入地了解它,您需要了解combineReducers

例子

rootReducer = combineReducers({potato: potatoReducer, tomato: tomatoReducer})
// This would produce the following state object
{
    potato: {
        // ... potatoes, and other state managed by the potatoReducer ...
    },
    tomato: {
        // ... tomatoes, and other state managed by the tomatoReducer, maybe some nice 
        // sauce? ...
    }
}

您可以通过对传递的对象中的 reducer 使用不同的键来控制状态键名称。例如,您可以要求combineReducers({ todos: myTodosReducer, counter: myCounterReducer })状态形状为{ todos, counter }

一个流行的约定是在他们管理的状态切片之后命名 reducer,因此您可以使用 ES6 属性简写表示法:combineReducers({ counter, todos }). 这相当于写作combineReducers({ counter: counter, todos: todos })

因此,当您使用时,您...state.list会因为combineReducers({ list: listReducer })simply combineReducers({ list})

了解更多请关注:combineReducers

于 2020-02-18T13:35:53.177 回答