[英]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.