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

标签 javascript reactjs react-router react-props

enter image description here我试图在成功获取数据后重定向页面,并且成功重定向页面,但是当它进入重定向页面时,我在控制台中获取类似 [object, object] 的数据,这是我的搜索页面和结果的代码页。我使用重定向来重定向页面,当我在结果页面中使用此 console.log("Don"+ this.props.location.state.movi​​e); 时,我没有得到数据,我得到的数据如下[object, object], [object, object] this 在控制台中。

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

关于javascript - react Js : Pass props to React Router's Link component Error,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59389415/

相关文章:

javascript - React-router条件渲染

javascript - 如何重启或刷新 Observable?

javascript - 使用 React router 进行 enzyme 集成测试测试 - 使用链接测试组件更新

reactjs - React 渲染链接包含一个变量

reactjs - 如何使用 ReactCSSTransitionGroup 在 React 中对元素高度进行动画处理?

javascript - 如何将 Jquery 代码转换为 React JS?

reactjs - 在 react-router-dom v6 中配置路由

javascript - 如何在当前 UTC 而不是客户端本地时间上创建此 'time ago' 函数引用?

javascript - Jquery Mobile 可折叠内容字体大小

javascript - 为什么正方形不适合放在 div 内