我有一个反应应用与反应路由器的导航。我尝试创建更新某些数据的表单。提交后数据通过ajax请求发送到服务器,如果ajex响应是“好”,那么用户必须重定向到另一个页面(在我的情况下,反应路由器中的url为/carwash
),并且关于成功更新的信息必须在远程页面中显示。反应重定向和传输信息到另一个页面
我试图通过3点differect的方式来做到这一点:
1)this.props.history.push('/carwash')
结果是例外:Uncaught TypeError: Cannot read property 'push' of undefined
2)browserHistory.push("/carwash")
,其结果是列表的浏览器被改变,但没有任何重定向
3)重定向绝对url无反应:window.location.replace("/owner.html#/carwash")
,结果成功,但我不知道如何通知目标页数据更新成功。
你能否解释一下在反应中重定向的最佳方式以及如何使用它?如何在用户重定向的页面上显示数据更新成功的信息不是不那么重要?
我的代码有以下几种观点:
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>
)
}
}
一些概念。您创建了一个单页面应用程序(SPA),然后使用“重定向”一词,这通常不适用于SPA。你是否真的想要浏览器刷新,或者你是否需要“反应”来呈现不同的组件/页面?它们实际上是两种不同的东西。 – Gregg
@Gregg对不起,但重定向它的反应的正式名称,反应路由器甚至有compinent - 设置重定向到另一个路线在您的应用程序来维护旧的URL [链接](https://github.com/ReactTraining/ react-router/blob/master/docs/API.md#重定向) –