1 javascript reactjs redux react-redux
我第一次尝试在 React 中设置 Redux,但似乎无法将我的初始状态从商店传递到组件。我的存储文件将状态设置为减速器的返回值。这是我将 this.props 记录到控制台时发生的情况
成分
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);Run Code Online (Sandbox Code Playgroud)
减速器
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
}
}Run Code Online (Sandbox Code Playgroud)
行动
import { EXAMPLE_ACTION } from './types'
export const exampleAction = text => ({
type: EXAMPLE_ACTION,
payload: text,
})Run Code Online (Sandbox Code Playgroud)
[编辑]
这是我在 mapStateToProps 中记录状态时发生的情况
import React from 'react';
import { createStore, combineReducers } from 'redux';
import reducers from '../reducers';
export const store = createStore(
combineReducers({
state: reducers
}),
);Run Code Online (Sandbox Code Playgroud)
使用 howcombineReducers()与state作为键传入的一起使用,您mapStateToProps()需要看起来像这样才能访问examplePropOne和examplePropTwo:
const mapStateToProps = state => ({
examplePropOne: state.state.examplePropOne,
examplePropTwo: state.state.examplePropTwo
});
Run Code Online (Sandbox Code Playgroud)
combineReducers() 产生的状态命名空间将每个 reducer 的状态传递给 combineReducers()
问题是:
export const store = createStore(
combineReducers({
state: reducers
}),
);
Run Code Online (Sandbox Code Playgroud)
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
});
Run Code Online (Sandbox Code Playgroud)
希望这有帮助!
| 归档时间: |
|
| 查看次数: |
4363 次 |
| 最近记录: |