[英]Redux dispatch not firing
我打给调度员的电话不起作用。 我要做的是在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
函数,因为您的函数是“ curried”的
function mapDispatch (dispatch) {
return {
dispatchShowPages (page) {
dispatch(changePageStatus(page))
}
}
}
export default connect(mapState, mapDispatch)(App)
我认为您不需要在reducer中使用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);
并且不要忘记从您的loadPages
文件中导出changePageStatus
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.