我在提交功能时尝试通过react- router-dom进行重定向,但我一直收到此错误

时间:2019-08-10 08:44:53

标签: function redirect react-router-dom

提交表格时,我希望更改路线,但出现错误,我也试图防止默认设置。请让我知道我在做什么错。我已经搜寻了几个小时。我想重定向到/ searchProducts

×
TypeError: Cannot read property 'props' of undefined
(anonymous function)
C:/Users/Test/Documents/GitHub/Ecommerce-Store/src/components/searchBar.js:10
   7 |  const { search } = productConsumer;
   8 | 
   9 |  useEffect(() => {
> 10 |    console.log(this.props.history);
     | ^  11 |  });
  12 | 
  13 |  const onChange = e => {
    import React, { useContext, useEffect, useRef } from 'react';
    import { ProductContext } from '../../src/context';

    const ProductFilter = props => {
      const productConsumer = useContext(ProductContext);
      const text = useRef('');
      const { search } = productConsumer;

      useEffect(() => {
        console.log(this.props.history);
      });

      const onChange = e => {
        if (text.current.value !== '') {
          search(e.target.value);
        } else {
        }
      };

      const onSubmit = e => {
        // e.preventDefault();
        // this.props.history.push('/path');
      };

      return (
        <form onSubmit={onSubmit()}>
          <input
            ref={text}
            type="text"
            placeholder="Search Keywords..."
            onChange={onChange}
            id=""
          />
        </form>
      );
    };

    export default ProductFilter;


1 个答案:

答案 0 :(得分:1)

要使用history对象,您需要一个withRouter HOC。

用HOC包装您的组件,您可以访问history对象。

import { withRouter } from "react-router-dom";

const ProductFilter = props => {
   ...
   useEffect(() => {
     console.log(props.history);   //Don't use this
   });

   const onSubmit = e => {
     // e.preventDefault();
     props.history.push('/path');  //Now you can access history object.
   };
   ...
}

export default withRouter(ProductFilter);

注意:在功能组件中,我们无权访问this