嗨,我是新来的反应。我进行了服务器调用,然后成功得到了响应。现在,我试图将相同的响应传递给另一条路线并在那里显示。我无法理解,我们如何在反应中做到这一点,就像在 Ember 中有一个方法 this.transitionTo('routepath', {data}) 然后这个数据在模型(params)的路由路径中可用。这怎么可能反应?我一定不会使用任何 Redux 或任何其他状态容器。我的代码如下:
import React, { Component } from 'react'
import axios from 'axios'
class Ernform extends Component {
constructor (props) {
super();
this.state = {
category: '',
zipcode: '',
age: '',
gender: '',
key: '',
data: null
};
}
onChange = (e) => {
this.setState({ [e.target.name]: e.target.value });
}
getPolicies = (e) => {
e.preventDefault();
const { category, zipcode, age, gender, key } = this.state;
axios.post(`http://localhost:4000/api/v1/quote`, { category, zipcode, age, gender, key })
.then(response => {
this.setState({data: response}); // I am setting response from server to the state property data
this.props.history.push('/details', {data: this.state.data})//I am trying to pass the data and trying to transition here.
});
}
render() {
const { category, zipcode, age, gender } = this.state;
return (
<div>
<form onSubmit={this.getPolicies}>
<label>
Category: <input type="text" name="category" value={category} onChange={this.onChange}/>
</label>
<label>
Zipcode: <input type="text" name="zipcode" value={zipcode} onChange={this.onChange}/>
</label>
<label>
Age: <input type="text" name="age" value={age} onChange={this.onChange}/>
</label>
<label>
Gender: <input type="text" name="gender" value={gender} onChange={this.onChange}/>
</label>
<button className="btn btn-primary btn-lg lead" type="submit">Get Policies</button>
</form>
</div>
);
}
}
export default Ernform
我的路由器是这样的:
import React from 'react'
import { Switch, Route } from 'react-router-dom'
import Ernform from './Ernform';
import Ernentry from './Ernentry'
import Erndetails from './Erndetails';
const Routing = () => (
<main>
<Switch>
<Route exact path='/' component={Ernentry}/>
<Route path='/auto' component={Ernform}/>
<Route path='/life' component={Ernform}/>
<Route path='/details' component={Erndetails}/> // added this route.
</Switch>
</main>
)
export default Routing
我的详细信息路由组件是这个
import React, { Component } from 'react'
class Erndetails extends Component {
constructor(props) { // Where would i get the data i transition with from that route.
console.log(props);
super()
}
render() {
return (
<div></div>
)
}
}
export default Erndetails
提前感谢很多人。
您的问题有两种解决方案,
I)第一种解决方案是以这种方式将推送对象中的数据与路由一起传递, this.props.history.push({ pathname: '/details', state: { detail: response.data } })
而不是你的路过。
在您的详细信息路由组件中,您可以通过props.location.state.detail
在构造函数或this.props.location.state.detail
componentDidMount 生命周期中使用来获取数据。
2)第二种解决方案是将其存储在本地存储中localStorage.setItem('token', data)
,然后使用localStorage.getItem('token')
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句