我很確定我有一些小的配置錯誤,因爲我沒有有這個工作。但是當我通過反應減少connect
調用打我的mapStateToProps
時,它正在注入我的減速器。我的設置是:狀態在mapStateToProps有錯誤的數據
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>© 2016</p>
</footer>
</div>
</div>
);
}
}
export default App;
導航欄-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;
和我的用戶名 - reducer.js:
const UsernameReducer = (state = '', action) => {
switch (action.type) {
case 'SET_USERNAME':
return action.username
default:
return state;
}
}
export default UsernameReducer;
如果我在mapStateToProps
呼叫做console.log(state)
,其顯示:
似乎state
有我在減速它。這看起來不對,我期待它具有username
道具。如果值得注意的話,那麼mapDispatchToProps
好像有正確的func被傳遞給它。
有人能告訴我我失蹤了什麼嗎?
它是正確的,因爲在'combineReducers'中'UsernameReducer'用作關鍵'{UsernameReducer:UsernameReducer}'。 –
@AlexanderT。在這裏做出什麼適當的改變?我對'state'對象期待'username'是否正確,我把它連接錯了?或者這是正確的連接,我誤解了它應該如何工作 – Jonesopolis
@Jonesopolis爲了瞭解爲什麼會發生,你需要看看'combineReducers'函數https://github.com/reactjs/redux/blob/ master/src/combineReducers.js#L102,https://github.com/reactjs/redux/blob/master/src/combineReducers.js#L103。你可以看到'combineReducers'使用過的鍵,在你的情況下你使用了兩個鍵'UsernameReducer','BuildsReducer',併爲這個'鍵'賦值減速器功能 –