React Js:将prop传递给React Router的Link组件错误

时间:2019-12-18 09:55:20

标签: javascript reactjs react-router react-props

enter image description here我尝试在成功获取数据后重定向页面,并且成功重定向页面,但是当它进入重定向页面时,我在控制台中收到action之类的数据,这是我的搜索页面代码,结果页。我使用重定向来重定向页面,当在结果页面中使用此[object, object]时,我没有得到数据。我在控制台中获得了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);

2 个答案:

答案 0 :(得分:1)

您需要传递字符串化的对象

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

您可以将其转换回对象,

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

答案 1 :(得分:0)

由于您在控制台中得到一个对象结果,所以我认为一切都很好。要测试该应用程序:

第1步 只需在电影状态下传递字符串类型值(例如电影名称)并进行测试即可。  如果结果可见。

第2步

传递设置为状态的电影对象,然后尝试使用控制台

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