我试图第一次在React中设置Redux,但似乎无法将初始状态从存储传递到组件。我的商店文件正在将状态设置为减速器的返回值。 Here is what happens when I log this.props to the console
组件
import React from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { exampleAction } from '../../actions';
class Header extends React.Component {
constructor(props) {
super(props);
this.state = {}
}
render() {
console.log(this.props)
return (
<div>
<p>this is {this.props.examplePropOne}</p>
</div>
);
}
}
const mapStateToProps = state => ({
examplePropOne: state.examplePropOne,
examplePropTwo: state.examplePropTwo
});
const mapDispatchToProps = dispatch => {
return bindActionCreators({ exampleAction }, dispatch)
}
export default connect(mapStateToProps, mapDispatchToProps)(Header);
减速器
import { EXAMPLE_ACTION } from './../actions/types'
const initialState = {
examplePropOne : 'Example Property One',
examplePropTwo : 'Example Property Two'
}
export default function (state = initialState, action) {
switch(action.type) {
case EXAMPLE_ACTION:
return {
...state,
examplePropOne: action.payload
}
default:
return state
}
}
操作
import { EXAMPLE_ACTION } from './types'
export const exampleAction = text => ({
type: EXAMPLE_ACTION,
payload: text,
})
[编辑]
Here is what happens when I log the state within mapStateToProps
import React from 'react';
import { createStore, combineReducers } from 'redux';
import reducers from '../reducers';
export const store = createStore(
combineReducers({
state: reducers
}),
);
答案 0 :(得分:2)
如何将combineReducers()
与作为密钥传递的state
一起使用,您的mapStateToProps()
必须看起来像这样,才能访问examplePropOne
和examplePropTwo
:
const mapStateToProps = state => ({
examplePropOne: state.state.examplePropOne,
examplePropTwo: state.state.examplePropTwo
});
combinedReducers()产生的状态将每个状态的名称空间命名为 传递给CombineReducers()的键下的reducer
问题在于:
export const store = createStore(
combineReducers({
state: reducers
}),
);
传递给state
的密钥combineReducers()
创建了state
的名称空间/属性。对于state
,使用名为mapStateToProps()
的参数,要求以state.state
的形式访问属性。可以通过改为传递给combineReducers()
的密钥一个更具描述性的名称来表示商店中正在使用的管理内容来解决此问题。例如,如果它与身份验证有关,则可以称为auth
之类的名称。看起来像:
export const store = createStore(
combineReducers({
auth: reducers
}),
);
// ...
const mapStateToProps = state => ({
examplePropOne: state.auth.examplePropOne,
examplePropTwo: state.auth.examplePropTwo
});
希望有帮助!