我打电话给调度员的工作没有用。我想要做的是在componentWillMount中触发一个调度程序来更新初始状态。
我的减速机设置如下:
// initial state
const pagesInitialState = {
begin: false,
basicInfo: false,
location: false,
education: false,
summary: false
}
const CHANGE_PAGE_STATUS = 'CHANGE_PAGE_STATUS';
// action creator
const changePageStatus = (page) => ({
type: CHANGE_PAGE_STATUS,
page
})
// dispatcher
export const dispatchShowPages = (page) =>
dispatch => {
console.log('not here');
dispatch(changePageStatus(page))
}
// reducer
export default function (state = pagesInitialState, action) {
switch (action.type) {
case CHANGE_PAGE_STATUS:
let pages = Object.assign({}, state);
let pageToChange = action.page;
if (pages.pageToChange === true) {
pages.pageToChange = false
} else {
pages.pageToChange = true
}
return pages
default:
return state
}
}
我的路线设置如下:
import React from 'react';
import {Route, Router} from 'react-router-dom';
import history from './history'
import Main from './components/containers/Main'
import { dispatchShowPages } from './reducers/loadPages'
class Routes extends React.Component {
componentWillMount () {
dispatchShowPages('begin')
}
render () {
return (
<Router history={history}>
<Main />
</Router>
)
}
}
export default Routes;
在我有一个不同的文件
ReactDOM.render(
<Provider store={store}>
<Routes />
</Provider>,
document.getElementById('app')
)
我希望调度员将初始状态中的“开始”从false更改为true。但似乎没有打到那个调度员。它得到dispatchShowPages但不在调度中。我在调度程序中的console.log('here')没有记录。我接线错了什么?
你的dispatchShowPages
函数从未被调用,因为你的函数是“咖喱”的
function mapDispatch (dispatch) {
return {
dispatchShowPages (page) {
dispatch(changePageStatus(page))
}
}
}
export default connect(mapState, mapDispatch)(App)
我认为你的减速机不需要dispatchShowPages
,因为你已经拥有了动作创造者。您需要做的就是使用Redux的connect
函数,如下所示:
import { connect } from 'react-redux';
import { changePageStatus } from './reducers/loadPages'
class Routes extends React.Component {
componentWillMount () {
this.props('begin')
}
render () {
return (
<Router history={history}>
<Main />
</Router>
)
}
}
const mapDispatchToProps = dispatch => ({
showPage: page => dispatch(changePageStatus(page))
});
export default connect(null, mapDispatchToProps)(Routes);
并且不要忘记从changePageStatus
文件中导出loadPages
。