React Js 使用 json 对象导航到另一个页面

Reat Js navigate with json object to another page

下面是我的代码,我从 api 获取数据,成功后我在 set_ProductDetails 中设置状态响应。我想将响应状态与结果一起传递给不同的组件和不同的页面并绑定数据。我正在使用 "react-router-dom": "^5.2.0".

Product_info.jsx

function GetProductDetails(products) {
  const history = useHistory();
  useEffect(() => {
    console.log("render", history.location.state);
  }, []);
  return (
    <>
      <div>
        <h1>Transaction Info</h1>
      </div>
    </>
  );
}
export default GetProductDetails

Product_query.jsx

function ProductSearch() {

  const [product_id, setProduct_id] = useState();
  const [product_search, set_ProductSearch] = useState({ product_id: "" });
  const [product_deatils, set_ProductDetails] = useState({ product_id: "" });

  const history = useHistory();
  
  //Handle the onSubmit
  function handleSubmit() {
    try {
      set_ProductSearch({ address: product_id });
      
    } catch (e) {
      alert(e.message);
    }
  }
  
   function onAPISuccess(data) {
     history.push("/product_info/GetProductDetails", { data }); 
    //here render blank screen 
    }

  useEffect(() => {
    
     const fetchData = async (product_id) => {
          try {
            const resp = await axios.post(
              config.SERVER_URL + "/api/getProductInfo/",
              product_id
            );
            set_ProductDetails(resp.data);
            onAPISuccess(data)
          } catch (err) {
            console.error(err);

        fetchData(product_search)
          .catch(console.error);
      
    }
  }, [product_search]);

return (
    <>
      <div class="input-group mb-3">
        <input
          type="text"
          class="form-control"
          aria-describedby="button-addon2"
          id="txt_address"
          name="address"
          placeholder="Address/Tx hash"
          onChange={(e) => setProduct_id(e.target.value)}
        ></input>

        <div class="input-group-append" style={{ color: "white" }}>
          <button
            class="btn btn-outline-success"
            type="button"
            id="button-addon2"
            onClick={() => handleSubmit()}
          >
            Search
          </button>
        </div>
      </div>
    </>
  );
}

export default ProductSearch

首页

export default function Home() {
return (
    <>
   <main>
        <div
          className="col-md-12"
          style={{
            background: "#fff",
            backgroundImage: `url(${Image})`,
            height: "245px",
          }}
        >
          <Container className="container-sm">
            <Row>
             
              <Col xs lg="5" className="justify-content-md-center">
                <div>
                  <ProductSearch></ProductSearch>
                </div>
              </Col>
            
            </Row>
          </Container>
        </div>
</main>
    <>
 )
}

history.push("/your_path",{..object you want to send})。然后在 history.push 重定向的组件中,通过说 history.location.state 访问该对象(这将 return 您在重定向时传递的对象)。