我正在重构一些代码以使用react-router-dom
而且我不理解为什么Route组件没有加载。成功登录后,用户应重定向到/packages
,但用户界面未更新且componentDidMount
api呼叫未触发。
loginActions.js
import * as types from './actionTypes'
import LoginApi from '../api/loginApi'
import createHistory from 'history/createBrowserHistory'
const history = createHistory()
export function loginUser(user) {
return function(dispatch) {
return LoginApi.login(user).then(creds => {
dispatch(loginUserSuccess(creds));
}).catch(error => {
throw(error);
});
}
}
export function loginUserSuccess(creds) {
sessionStorage.setItem('credentials', JSON.stringify(creds.data));
history.push('/packages');
return {
type: types.LOGIN_USER_SUCCESS,
state: creds.data
}
}
PackageContainer.jsx
import React from 'react'
import {connect} from 'react-redux'
import {loadPackages} from '../../actions/packageActions'
import PackageList from './PackageList'
import {withRouter} from 'react-router-dom'
class PackageContainer extends React.Component {
constructor(props, context) {
super(props, context);
}
componentDidMount() {
this.props.dispatch(loadPackages()); // NOT FIRING
}
render() {
return (
<div className="col-lg-12">
{this.props.results ?
<PackageList results={this.props.results} /> :
<h3>No Packages Available</h3>}
</div>
);
}
}
PackageContainer.propTypes = {
results: ImmutablePropTypes.list.isRequired,
};
const mapStateToProps = (state, ownProps) => {
return {
packages: state.get('packages'),
results: !state.getIn(['packages','packages','results']) ? List() : state.getIn(['packages','packages','results'])
};
}
PackageContainer = withRouter(connect(mapStateToProps)(PackageContainer))
export default PackageContainer
App.jsx
import LoginFormContainer from './components/Login/LoginFormContainer'
import PackageContainer from './components/Package/PackageContainer'
class App extends Component {
render() {
return (
<Grid>
<Navbar>
<Navbar.Header>
<Navbar.Brand><h3>Mythos</h3></Navbar.Brand>
</Navbar.Header>
</Navbar>
<Row className="content">
<Col xs={12} md={12}>
<Switch>
<Route exact path='/' component={LoginFormContainer} />
<Route exact path='/packages' component={PackageContainer} />
</Switch>
</Col>
</Row>
</Grid>
)
}
}
export default App
修改
将historyApiFallback: true
添加到webpack配置中,修复了未加载的组件,但仍需要重新加载页面。
devServer: {
contentBase: './dist',
hot: true,
proxy: [{
context: ['/idm', '/vsms'],
target: 'http://vsdm-gw-dev.labviaaq.com'
}],
historyApiFallback: true
}