mapStateToProps中的状态数据错误

时间:2016-12-06 15:22:24

标签: reactjs redux react-redux

我很确定我有一些小配置错误,因为我确实有这个工作。但是当我通过react-redux mapStateToProps调用我的connect时,它会被注入我的Reducer。我的设置是:

App.js:

import React from 'react';
import BuildsContainer from '../containers/builds-container';
import NavBarContainer from '../containers/nav-bar-container';

class App extends React.Component {
    constructor(props) {
        super(props);  
    }

    render() {
        return (
            <div>
                <NavBarContainer />

                <div className="container body-content">

                    <BuildsContainer />

                    <hr />
                    <footer>
                        <p>&copy; 2016</p>
                    </footer>

                </div>
            </div>
        );
    }
}

export default App;

NAV-BAR-container.js:

import { connect } from 'react-redux'
import NavBar from '../components/nav-bar'
import  { setUsername } from '../actions/actions'

const mapStateToProps = (state) => {
    console.log(state)  
    return {username: state.username}
}

const mapDispatchToProps = ({ 
    setUsername: setUsername
}) 

const NavBarContainer = connect(
mapStateToProps,
mapDispatchToProps
)(NavBar)

export default NavBarContainer

我的主减速器,reducer.js:

import { combineReducers } from 'redux'
import UsernameReducer from './username-reducer'
import BuildsReducer from './builds-reducer'

const BuildWatcherApp = combineReducers({
    UsernameReducer,
    BuildsReducer
})

export default BuildWatcherApp;

和我的username-reducer.js:

const UsernameReducer = (state = '', action) => {
    switch (action.type) {
        case 'SET_USERNAME':
            return action.username
        default:
            return state;
    }
}

export default UsernameReducer;

我在console.log(state)电话中mapStateToProps所做的事情,显示:

enter image description here

state似乎有我的减速器。这看起来并不正确,我期待它拥有username道具。如果值得注意,mapDispatchToProps似乎确实传递了正确的函数。

有人可以告诉我我错过了什么吗?

1 个答案:

答案 0 :(得分:0)

结果表明我的问题出在combineReducers

const BuildWatcherApp = combineReducers({
   UsernameReducer,
   BuildsReducer
})

我的减速机名称与我的州的属性不匹配。将此更改为:

const BuildWatcherApp = (state = {}, action) => ({
    username: UsernameReducer(state.username, action),
    builds: BuildsReducer(state.builds, action)
})

修好了。