我有一个带有简单登录功能的 React.js 项目。用户获得授权后,我调用 history.push 方法,该方法更改地址栏中的链接,但不呈现新组件。(我使用浏览器路由器(
我的索引.js组件:
ReactDOM.render(
<Provider store={createStore(mainReducer, applyMiddleware(thunk))}>
<BrowserRouter>
<Main />
</BrowserRouter>
</Provider>,
document.getElementById('root')
);
我的主.js组件:
const Main = (props) => {
return (
<Switch>
<Route exact path="/" component={Signin} />
<Route exact path="/servers" component={Servers} />
</Switch>
)}
export default withRouter(Main);
我的动作创建者:
export const authorization = (username, password) => (dispatch) =>
new Promise ((resolve, reject) => {
fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
username: username,
password: password,
})
}).then( response => {
if (response.ok) {
response.json().then( result => {
console.log("API reached.");
dispatch(logUserIn(result.token));
resolve(result);
})
} else {
let error = new Error(response.statusText)
error.response = response
dispatch(showError(error.response.statusText), () => {throw error})
reject(error);
}
});
});
我的登录.js组件:
handleSubmit(event) {
event.preventDefault();
this.setState({ isLoading: true })
const { username, password } = this.state;
this.props.onLoginRequest(username, password, this.props.history).then(result => {
console.log("Success. Token: "+result.token); //I do get "success" in console
this.props.history.push('/servers') //Changes address, does not render /servers component
});
}
const mapActionsToProps = {
onLoginRequest: authorization
}
最奇怪的是,如果我将我的 handleSubmit(( 方法更改为此 - 一切都完美运行:
handleSubmit(event) {
event.preventDefault();
this.setState({ isLoading: true })
const { username, password } = this.state;
this.props.onLoginRequest(username, password, this.props.history).then(result => {
console.log("Success. Token: "+result.token);
//this.props.history.push('/servers')
});
this.props.history.push('/servers')
}
如果我尝试从componentWillReceiveProps(newProps)
方法推送历史记录,也会出现同样的问题 - 它会更改地址但不呈现新组件。有人可以解释为什么会发生这种情况以及如何解决它吗?
如果有人感兴趣 - 发生这种情况是因为应用程序在推送历史记录之前正在渲染。当我将历史记录推送放入我的操作中时,但在结果转换为 JSON 之前,它开始工作,因为现在它推送历史记录,然后才渲染应用程序。
export const authorization = (username, password, history) => (dispatch) =>
new Promise ((resolve, reject) => {
fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
username: username,
password: password,
})
}).then( response => {
if (response.ok) {
//################################
//This is where I put it
history.push("/servers");
//################################
response.json().then( result => {
dispatch(logUserIn(result.token));
resolve(result);
})
} else {
let error = new Error(response.statusText)
error.response = response
dispatch(showError(error.response.statusText), () => {throw error})
reject(error);
}
});
});
您需要申请 withRouter 才能在每个使用"push"的组件中使用 this.props.history.push('/page'(
import { withRouter } from 'react-router-dom';
.....
export default
withRouter(MoneyExchange);
这在使用推送时很重要。
首先,创建一个使用历史包的历史对象:
// src/history.js
import { createBrowserHistory } from 'history';
export default createBrowserHistory();
然后将其包装在主路由器组件中。
import { Router, Route, Link } from 'react-router-dom';
import history from './history';
ReactDOM.render(
<Provider store={store}>
<Router history={history}>
<Fragment>
<Header />
<Switch>
<SecureRoute exact path="/" component={HomePage} />
<Route exact path={LOGIN_PAGE} component={LoginPage} />
<Route exact path={ERROR_PAGE} component={ErrorPage} />
</Switch>
<Footer />
</Fragment>
</Router>
</Provider>)
在这里,在调度请求后,重定向到主页。
function requestItemProcess(value) {
return (dispatch) => {
dispatch(request(value));
history.push('/');
};
}
应该有帮助:)
尝试使用自定义历史记录和路由器而不是浏览器路由器。安装历史记录后:
yarn add history
创建自定义浏览器历史记录:
import { createBrowserHistory } from "history";
export default createBrowserHistory();
在设置中使用路由器而不是浏览器路由器:
import history from "your_history_file";
ReactDOM.render(
<Provider store={createStore(mainReducer, applyMiddleware(thunk))}>
<Router history={history}>
<Main />
</Router>
</Provider>,
document.getElementById('root')
);
或者,如果您不想使用自定义历史记录文件并从那里导入,则可以将其直接放入索引中.js:
import { createBrowserHistory } from "history";
const history = createBrowserHistory();
ReactDOM.render(
<Provider store={createStore(mainReducer, applyMiddleware(thunk))}>
<Router history={history}>
<Main />
</Router>
</Provider>,
document.getElementById('root')
);
我使用反应电子样板,在使用MemoryRouter
时遇到问题
使用history.push('/someUrl')
不起作用...
只需使用组件中的exact
属性,initialEntries
设置默认路由。
<Router initialEntries={['/']}>
<Switch>
<Route exact path="/" component={LoginScreen} />
<Route exact path="/session" component={SessionScreen} />
</Switch>
</Router>
不处理这个->
handleSubmit(event) {
event.preventDefault();
this.setState({ isLoading: true })
const { username, password } = this.state;
this.props.onLoginRequest(username, password, this.props.history).then(result => {
console.log("Success. Token: "+result.token); //I do get "success" in console
this.props.history.push('/servers') //Changes address, does not render /servers component
});
}
const mapActionsToProps = {
onLoginRequest: authorization
}
因为在这个handleSubmit
方法中,你在 promise 中调用this.props.history.push()
,因此this
指向 Promise 的实例而不是您当前的类实例。
试试这个 ->
handleSubmit(event) {
event.preventDefault();
const { history: { push } } = this.props;
this.setState({ isLoading: true })
const { username, password } = this.state;
this.props.onLoginRequest(username, password, this.props.history).then(result => {
console.log("Success. Token: "+result.token); //I do get "success" in console
push('/servers') //Changes address, does not render /servers component
});
}
const mapActionsToProps = {
onLoginRequest: authorization
}
现在在此声明中 ->
handleSubmit(event) {
event.preventDefault();
this.setState({ isLoading: true })
const { username, password } = this.state;
this.props.onLoginRequest(username, password, this.props.history).then(result => {
console.log("Success. Token: "+result.token);
//this.props.history.push('/servers')
});
this.props.history.push('/servers')
}
您正确地调用了this.props.history.push((,因为它超出了承诺并引用了Current Class实例。