我有一个带有react-router的react应用程序用于导航。我尝试创建更新一些数据的表单。提交后,数据通过ajax请求发送到服务器,如果ajax响应为“Ok”,则用户必须重定向到另一个页面(在我的例子中,react-router中的url是/carwash
)并且有关成功更新的信息必须显示在目标页面中。
我尝试通过 3 种不同的方式来做到这一点:
1) this.props.history.push('/carwash')
结果出现异常:Uncaught TypeError: Cannot read property 'push' of undefined
2) browserHistory.push("/carwash")
,结果是浏览器中的列表发生了变化,但没有任何重定向
3)绝对网址重定向,无需 react :window.location.replace("/owner.html#/carwash")
,结果成功,但我不明白如何通知目的地页面数据更新成功。
你能解释一下 react 中重定向的最佳方法是什么以及如何使用它吗?同样重要的是如何通知用户将被重定向的页面数据已成功更新?
我的代码具有以下 View :
import React from 'react';
import {Router} from 'react-router';
import Loading from './form/loading.jsx';
export default class EditCarWashForm extends React.Component{
static contextTypes = {
router: React.PropTypes.object.isRequired
};
constructor(props) {
super(props);
this.state = {
name : {value : constants.EMPTY_FIELD, isValid : false},
address : {value : constants.EMPTY_FIELD, isValid : true},
isCarWashDownload : true
};
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(e) {
e.preventDefault();
let carWashData = {some logic}
$.ajax({
url: '/carwash/',
type: 'POST',
async: true,
cache: false,
contentType: 'application/json',
data: JSON.stringify(carWashData),
dataType: 'json',
success: function(data) {
if (data.message == 'Ok'){
// browserHistory.push("/owner.html#/carwash")
this.props.history.push('/carwash');
// window.location.replace("/owner.html#/carwash");
}
}.bind(this),
})
};
render(){
let data = <Loading/>
if (this.state.isCarWashDownload) {
data =
<form onSubmit={this.handleSubmit} id="addCarWashForm">
<FormInputField
title="Name*:"
placeholder="Name"
name="name"
required={true}
maxLength={50}
defaultValue={this.state.name.value}
/>
<FormInputField
title="Adress:"
placeholder="Adress"
name="address"
maxLength={200}
/>
<div className="form-group">
<div className="col-sm-offset-2 col-sm-10">
<button type="submit">Update</button>
</div>
</div>
</form>
}
return (
<div>
{data}
</div>
)
}
}
最佳答案
尝试导入 browserHistory,例如:
// Somewhere like a Redux middleware or Flux action:
import { browserHistory } from 'react-router'
// Go to /some/path.
browserHistory.push('/some/path')
关于javascript - react 重定向并将信息传输到另一个页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39963830/