javascript - React/Redux:为什么我在 this.props 中的属性未定义?
问题描述
我第一次尝试在 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);
减速器
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,
})
[编辑]
这是我在 mapStateToProps 中记录状态时发生的情况
import React from 'react';
import { createStore, combineReducers } from 'redux';
import reducers from '../reducers';
export const store = createStore(
combineReducers({
state: reducers
}),
);
解决方案
使用 how combineReducers()
is used withstate
作为键传入,您mapStateToProps()
需要看起来像这样才能访问examplePropOne
and examplePropTwo
:
const mapStateToProps = state => ({
examplePropOne: state.state.examplePropOne,
examplePropTwo: state.state.examplePropTwo
});
combineReducers() 产生的状态命名空间将每个 reducer 的状态在其键下传递给 combineReducers()
问题是:
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
});
希望这会有所帮助!
推荐阅读
- android - BottomNavigationView 设置从某个 url 下载的自定义图标
- jquery - Jquery Datatable 列调整大小无法按预期工作,定义了“columnDefs”列宽
- svg - http 到 https 迁移后解析 SVG 文件的问题
- php - 通过 React 将数据发布到 laravel
- mysql - 从选择查询 MySql 插入记录其他更新
- crystal-reports - 格式化跨越多行的超链接
- python - 如何在 python 字典中保持循环以搜索值?
- javascript - 使用 Moment.js 从日期数组中查找最近的第二天
- asp.net-mvc - 找到多个与 URL 错误 MVC 5 匹配的控制器类型
- c# - 拆分和单元测试 linq-query