Redux Reducer 只是 returns 一个动作的值而不是一个状态?
Redux Reducer that simply returns an action's value and not a state?
我有一个 Container、一个 actionsCreator 和一个 reducer。在下面的代码中,是什么使 Reducer 能够 return action.text
而不是更新的状态对象?我认为减速器必须总是 return 状态。
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)。
name
只是状态的一部分。而action.text
是更新后的状态。
在 combineReducers({ name })
之后,状态树如下所示:
{
name: '..'
}
此外,redux 并没有限制你只能使用对象作为你的状态。如果你直接将 name
传递给 createStore()
而没有 combineReducers
,你的整个状态将变成一个纯字符串。
I thought reducers had to always return states.
没有。 Reducer 必须始终 return data。而且,你不应该return状态,而是一个新的对象(或其他数据类型)。
因此,在您的案例中,每次调度 HELLO_WORLD_NAME_UPDATE
操作时,reducer return 都是一个新字符串(或 text
的任何数据类型)。它不关心状态中已经存在的内容和 return 新的文本字符串。
我有一个 Container、一个 actionsCreator 和一个 reducer。在下面的代码中,是什么使 Reducer 能够 return action.text
而不是更新的状态对象?我认为减速器必须总是 return 状态。
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)。
name
只是状态的一部分。而action.text
是更新后的状态。
在 combineReducers({ name })
之后,状态树如下所示:
{
name: '..'
}
此外,redux 并没有限制你只能使用对象作为你的状态。如果你直接将 name
传递给 createStore()
而没有 combineReducers
,你的整个状态将变成一个纯字符串。
I thought reducers had to always return states.
没有。 Reducer 必须始终 return data。而且,你不应该return状态,而是一个新的对象(或其他数据类型)。
因此,在您的案例中,每次调度 HELLO_WORLD_NAME_UPDATE
操作时,reducer return 都是一个新字符串(或 text
的任何数据类型)。它不关心状态中已经存在的内容和 return 新的文本字符串。