3

我有一个容器、一个 actionsCreator 和一个 reducer。在下面的代码中,是什么让 Reducer 返回action.text而不是更新的状态对象?我认为减速器必须始终返回状态。

HelloWorldContainer.jsx

 import { connect } from 'react-redux';
 import HelloWorld from '../components/HelloWorld';
 import * as actionCreators from '../actions/helloWorldActionCreators';

 const mapStateToProps = (state) => ({ name: state.name });

 export default connect(mapStateToProps, actionCreators)(HelloWorld);

helloWorldActionCreators.jsx

 import { HELLO_WORLD_NAME_UPDATE } from '../constants/helloWorldConstants';

 export const updateName = (text) => ({   
   type: HELLO_WORLD_NAME_UPDATE,  
   text, 
 });

helloWorldReducer.jsx

 import { combineReducers } from 'redux';
 import { HELLO_WORLD_NAME_UPDATE } from '../constants/helloWorldConstants';

 const name = (state = '', action) => {
   switch (action.type) {
     case HELLO_WORLD_NAME_UPDATE:
       return action.text
     default:
       return state;
   }
 };

 const mainReducer = combineReducers({ name });

 export default mainReducer;

(代码来源:React on Rails)。

4

2 回答 2

3

name只是状态的一部分。并且action.text 更新的状态。

之后combineReducers({ name }),状态树如下所示:

{
  name: '..'
}

此外,redux 并没有限制你只能使用 object 作为你的 state。如果你直接传递namecreateStore()without combineReducers,你的整个状态将变成一个纯字符串。

于 2017-03-20T07:36:39.310 回答
2

我认为减速器必须始终返回状态。

不,Reducer 必须始终返回数据。此外,您不应该返回状态,而是返回一个新对象(或其他数据类型)。

因此,在您的情况下,reducertext每次HELLO_WORLD_NAME_UPDATE调度操作时都会返回一个新字符串(或任何数据类型)。它不关心状态中已经存在的内容并返回一个新的文本字符串。

于 2017-03-20T07:55:04.703 回答