簡體   English   中英

React Js:將道具傳遞給 React Router 的 Link 組件錯誤

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

在此處輸入圖片說明 我試圖在成功獲取數據后重定向頁面,我成功重定向頁面,但是當它進入重定向頁面時,我在控制台中獲取像[object, object]這樣的數據[object, object]這是我的搜索頁面和結果頁面的代碼。 我使用重定向來重定向頁面,當我使用這個console.log("Don" + this.props.location.state.movie);時我沒有得到數據console.log("Don" + this.props.location.state.movie); 在結果頁面中,我在控制台中獲取了像[object, object], [object, object]這樣的數據。

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);

這是我想顯示數據的另一個文件。

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);

您需要傳遞字符串化的對象,

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

您可以將其轉換回對象,

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

由於您在控制台中得到一個對象結果,我認為那里一切正常。 要測試應用程序:

步驟 1只需在電影狀態和測試中傳遞像電影名稱這樣的字符串類型值。 如果結果可見。

第2步

傳遞狀態中設置的電影對象並嘗試控制台

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM