简体   繁体   中英

React Js: Pass props to React Router's Link component Error

在此处输入图片说明 I am trying to redirect page after successful fetch get data and I redirect page successfully but when it goes in redirect page I getting data like [object, object] in console here is my code for search page and result page. I used redirect to redirect page and I am getting not data when I used this console.log("Don" + this.props.location.state.movie); in result page I am getting data like [object, object], [object, object] this in console.

import React, { Component } from "react";
import Datee from "./Date";
import { withRouter } from "react-router";
import "./index";

class DriverReport extends Component {
  constructor(props) {
    super(props);
    this.state = {
      selectOptions: [],
      movie: [],
      isHidden: true
    };

    this.handleSubmit = this.handleSubmit.bind(this);
    this.handleChange = this.handleChange.bind(this);
    this.toggleHidden = this.toggleHidden.bind(this);
  }

  toggleHidden() {
    this.setState({
      isHidden: !this.state.isHidden
    });
  }

  async handleSubmit(e) {
    let authToken = localStorage.getItem("Token");
    try {
      const from = e.target.elements.from.value;
      const to = e.target.elements.to.value;
      const selections = [...e.target.elements.selectOptions.options].filter(
        opt => opt.selected
      );
      const selectedValues = selections.map(opt => opt.value);
      const selectedString = selectedValues.join(",");
      e.preventDefault();
      const res = await fetch(
        `http://localhost:8000/api/1/deliveries/report/?date__lte=${to}&date__gte=${from}&user=${selectedString}`,
        {
          method: "GET",
          headers: {
            Accept: "application/json",
            "Content-Type": "application/json",
            Authorization: "Bearer " + JSON.parse(authToken)
          }
        }
      );
      const movie = await res.json();
      console.log(movie);
      this.setState({
        movie
      });
      // this.props.history.push("/driverreport");
      //this.props.history.push({
       // pathname: "/driverreport",
      //  state: {
      //    movie: movie
     //   }
      });**
    } catch (e) {
      console.log(e);
    }
  }

  handleChange = e => {
    let target = e.target;
    let name = target.name;
    //here
    let value = Array.from(target.selectedOptions, option => option.value);
    this.setState({
      [name]: value
    });
  };

  render() {
    return (
      <span>
        {!this.state.hidden && (
          <div id="driver" class="modal">
            <a
              href="# "
              rel="modal:close"
              className="float-right text-white h4"
              style={{
                background: "black",
                borderRadius: "50%",
                padding: "10px",
                height: "32px",
                lineHeight: "10px",
                position: "relative",
                left: "30px",
                top: "-18px"
              }}
            >
              &times;
            </a>
            <p className="mod" style={{ marginTop: "40px" }}>
              DRIVERS REPORT
            </p>

            <form style={{ marginTop: "20px" }} onSubmit={this.handleSubmit}>
              <div>
                <Datee />
              </div>

              <div className="form-group" style={{ marginTop: "20px" }}>
                <label style={{ opacity: "0.6", fontSize: "10px" }}>
                  CHOOSE A DRIVER
                </label>
                <select
                  name="selectOptions"
                  style={{ width: "390px" }}
                  // multiple={true}
                  onChange={this.handleChange}
                  value={this.state.selectOptions}
                  class="form-control donn"
                >
                  <option value="1">Choose Driver</option>
                  <option value="1">General Score</option>
                  <option value="2">Dynamic</option>
                  <option value="3">Speed</option>
                  <option value="4">Fuel Save</option>
                </select>
              </div>

              <div style={{ marginTop: "50px" }}>
                <center>
                  <button
                    type="submit"
                    value="Get Data"
                    className="btn btn-login text-white font-weight-bolder boxx "
                    id="button"
                    onClick={this.toggleHidden}
                    style={{
                      height: "40px",
                      fontSize: "13px",
                      lineHeight: "30px",
                      width: "200px",
                      background: "rgba(183, 28, 28, 1)",
                      border: "none",
                      color: "white",
                      margin: "auto"
                    }}
                  >
                    RAPORT
                  </button>
                </center>
              </div>
            </form>
             {this.state.movie.length > 0 && (
              <Redirect
                to={{
                  pathname: "/driverreport",
                  state: { movie: this.state.movie }
                }}
              />
            )} 

          </div>
        )}
      </span>
    );
  }
}
export default withRouter(DriverReport);

and here it is another file where i want to display daata.

import React, { Component } from "react";
import ReactToExcel from "react-html-table-to-excel";
import DriverReport from "../DriverReport";
import config from "../../Main";
import { withRouter } from "react-router";

class DriverReportt extends Component {
  constructor(props) {
    super(props);
    this.state = {

    };
  }

  render() {
    console.log("Don" + this.props.location.state.movie);
    return (
      <div className="container" style={{ marginTop: "50px" }}>
        <h1> Result Here </h1>
      </div>
    );
  }
}
export default withRouter(DriverReportt);

You need to pass the stringified object,

<Redirect
   to={{
         pathname: "/driverreport",
         state: { movie: JSON.stringify(this.state.movie) }
      }}
/>

You can convert it back to object,

console.log("Don" + JSON.parse(this.props.location.state.movie));

Since you are getting an object result in the console, I think everything is okay there. To test the application:

Step 1 Just pass the string type value like movie name in movie state and test. If the result is visible.

Step 2

Pass the movie object set in state and try the console like

console.log("Don: ",  this.props.location.state.movie);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM