我使用以下堆栈:
“依赖关系”:{
“ preact”:“ ^ 8.2.1”,
“ preact-compat”:“ ^ 3.17.0”,
“ preact-redux”:“ ^ 2.0.3”,
“ preact-router”:“ ^ 2.5.5”,
“ redux”:“ ^ 3.7.2”
}
与preact-cli结合使用。然后当我想渲染以下应用程序时:
import { h, Component } from 'preact'
import { Router } from 'preact-router'
import { Provider } from 'preact-redux'
import store from '../store'
import Header from './header'
import Home from '../routes/home'
import Profile from '../routes/profile'
import Login from '../routes/login'
export default class App extends Component {
/** Gets fired when the route changes.
* @param {Object} event "change" event from [preact-router](http://git.io/preact-router)
* @param {string} event.url The newly routed URL
*/
handleRoute = e => {
this.currentUrl = e.url
};
render() {
return (
<div id="app">
<Provider store={store}>
<Header />
<Router onChange={this.handleRoute}>
<Home path="/" />
<Login path="/login" />
<Profile path="/profile" user="me" />
<Profile path="/profile/:user" />
</Router>
</Provider>
</div>
)
}
}
那么仅呈现
Header
组件,但忽略路由。你知道为什么会这样吗?当我删除Provider
组件时,它工作正常。谁能帮助我找到这种不良行为的原因?为了完整性:
reducers / index.js
import { combineReducers } from 'redux'
import authReducer from './auth'
const rootReducer = combineReducers({
auth: authReducer
})
export default rootReducer
reducers / auth.js
import * as consts from '../constants/auth'
const initialState = {}
const reducer = (state = initialState, action) => {
switch (action.type) {
case consts.LOGIN_PROCESSING:
return {
...state,
isLoginProcessing: true,
isLoginSuccess: true,
loginError: null
}
case consts.LOGIN_FAILURE:
return {
...state,
isLoginProcessing: false,
isLoginSuccess: false,
loginError: action.payload.error
}
case consts.LOGIN_SUCCESS:
return {
...state,
user: action.payload.user,
isLoginProcessing: false,
isLoginSuccess: true,
loginError: null
}
case consts.REGISTER_PROCESSING:
return {
...state,
isRegisterProcessing: true,
isRegisterSuccess: true,
registerError: null
}
case consts.REGISTER_FAILURE:
return {
...state,
isRegisterProcessing: false,
isRegisterSuccess: false,
registerError: action.payload.error
}
case consts.REGISTER_SUCCESS:
return {
...state,
user: action.payload.user,
isRegisterProcessing: false,
isRegisterSuccess: true,
registerError: null
}
case consts.LOGOUT_PROCESSING:
return {
...state,
isLogoutProcessing: true,
isLogoutSuccess: true,
logoutError: null
}
case consts.LOGOUT_FAILURE:
return {
...state,
isLogoutProcessing: false,
isLogoutSuccess: false,
logoutError: action.payload.error
}
case consts.LOGOUT_SUCCESS:
return {
...state,
user: null,
isLogoutProcessing: false,
isLogoutSuccess: true,
logoutError: null
}
default:
return state
}
}
export default reducer
最佳答案
我现在自己解决了。解决方案非常简单。您只需要添加一个根组件作为redux提供者的子代即可:
<Provider store={store}>
<div> // <-- adding this root element is the solution
<Header />
<Router onChange={this.handleRoute}>
<Home path="/" />
</Router>
</div>
</Provider>