gpt4 book ai didi

javascript - React/Redux : Why are my my properties in this. Prop 未定义?

转载 作者:行者123 更新时间:2023-11-30 11:12:15 25 4
gpt4 key购买 nike

我第一次尝试在 React 中设置 Redux,我似乎无法将我的初始状态从商店传递到组件。我的存储文件将状态设置为 reducer 的返回值。 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);

reducer

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
}
}

Action

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
}),
);

最佳答案

随着 combineReducers() 与作为键传入的 state 一起使用,您的 mapStateToProps() 需要看起来像这样访问 examplePropOneexamplePropTwo:

const mapStateToProps = state => ({
examplePropOne: state.state.examplePropOne,
examplePropTwo: state.state.examplePropTwo
});

鉴于combineReducers() :

The state produced by combineReducers() namespaces the states of each reducer under their keys as passed to combineReducers()

问题是:

export const store = createStore(
combineReducers({
state: reducers
}),
);

传递给 combineReducers() 的键 state 创建了 state 的命名空间/属性。 mapStateToProps() 的参数名为 state,要求属性作为 state.state 访问。这可能可以通过为传递给 combineReducers() 的键提供一个更具描述性的名称来解决,该名称代表商店中用于管理的内容。例如,如果它与身份验证有关,则可以将其称为auth。它看起来像:

export const store = createStore(
combineReducers({
auth: reducers
}),
);

// ...

const mapStateToProps = state => ({
examplePropOne: state.auth.examplePropOne,
examplePropTwo: state.auth.examplePropTwo
});

希望对您有所帮助!

关于javascript - React/Redux : Why are my my properties in this. Prop 未定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53216892/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com