【问题标题】:How to pass data returned from server and then transition to another route with returned data?如何传递从服务器返回的数据,然后使用返回的数据转换到另一个路由?
【发布时间】:2018-08-17 20:42:58
【问题描述】:

嗨,我是新来的反应。我进行了服务器调用,然后成功得到了响应。现在,我正在尝试将相同的响应传递给另一条路线并在那里显示。我无法理解,我们如何在反应中做到这一点,就像在 Ember 中有一个方法 this.transitionTo('routepath', {data}) 然后这些数据在模型(参数)的路由路径中可用。这怎么可能反应?我一定不会使用任何 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

非常感谢各位。

【问题讨论】:

  • 我建议研究一下 redux。当您从服务器获取异步值时,您将一个操作(包含这些值)分派到 redux 存储。您还重定向到新页面。在那个新页面中,它可以从存储中读取值来显示它们。
  • 我一定不会使用 redux 或任何其他状态容器。

标签: javascript reactjs react-router react-redux


【解决方案1】:

您的问题有两种解决方案,

I) 第一个解决方案是通过这种方式将推送对象中的数据与路由一起传递, this.props.history.push({ pathname: '/details', state: { detail: response.data } })

而不是你的传球。

在您的详细路由组件中,您可以通过在构造函数中使用 props.location.state.detail 或在 componentDidMount 生命周期中使用 this.props.location.state.detail 来获取数据。

2) 第二种解决方案是使用localStorage.setItem('token', data) 将其存储在本地存储中,然后使用localStorage.getItem('token') 访问它

【讨论】:

    【解决方案2】:

    我认为react-router 不允许。我的建议是使用LocalStorage#setItem 方法将您的数据存储在LocalStorage 中,然后在您的下一个组件中使用LocalStorage#getItem 检索它。

    您也可以将 Redux 用于您的状态并在屏幕之间共享数据,但作为初学者,您需要更多时间来学习它。

    你也可以使用 React 的 Context API,但作为 Redux,它会花费你更多的时间,即使它比 Redux 更容易。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-07-14
      • 2016-12-09
      • 1970-01-01
      • 1970-01-01
      • 2017-06-17
      • 1970-01-01
      • 2018-01-09
      相关资源
      最近更新 更多