【问题标题】:How can I on Submit my Form redirect the Results to another Page in React我如何在提交表单时将结果重定向到 React 中的另一个页面
【发布时间】:2019-09-04 04:39:07
【问题描述】:

我试图让搜索结果显示在 React Js 的另一个页面上。现在,当我提交我的搜索表单时,它会在我不想要的同一页面上显示结果。在过去的 4 个小时里,我一直在尝试这样做(我是 ReactJS 的新手),我在网上看到了很多建议,但似乎没有像我希望的那样奏效。

我什至尝试过使用 react redux、react router 和更多在线示例,但没有用,别做错了。

我该如何处理它?我希望有人可能让我在下面提供的代码方面走上正轨,也欢迎您的建议/反馈。

提前谢谢你。

这是我负责表单的搜索引擎组件

const SearchEngine = (props) => {

        return (

            <div>
                <h3 className="spacer">Search Engine</h3>
                <form onSubmit={props.getTrend}>
                <div class="input-group md-form form-sm form-2 pl-0">

                        <input class="form-control my-0 py-1 red-border" type="text" name="keyword" placeholder="Enter your keyword" aria-label="Search" />

                    <div class="input-group-append">
                      <button class="input-group-text red lighten-3" id="basic-text1"><i class="fa fa-search text-grey" aria-hidden="true"></i></button>
                    </div>
                </div>
                </form>
            </div>
        );
}

export default SearchEngine;

这是我想要显示结果的结果组件

const Results = (props) => (

    <div>

        Hello

    </div>

);


 export default Results;

【问题讨论】:

    标签: reactjs react-redux react-router search-form


    【解决方案1】:

    收到您的 api 调用后,您可以发起推送并移动到另一个页面。对于你来说,它可能看起来像这样。

        getTrend = async (e) => {
        e.preventDefault();
    
        const keyword = e.target.elements.keyword.value;
    
        const api_call = await fetch(`http://localhost:8081/trend/twitter?keyword=${keyword}`); //make API call
    
        const data = await api_call.json(); 
    
    
       if (keyword) {
            this.setState({
              tweets: data
            });
            console.log(this.state.tweets);
            this.props.history.push({
      pathname: '/results',
      state: { detail: data }
    })
          } 
          else {
            this.setState({
              tweets: undefined,
              error: "Please enter the values"
            });
          }
      }
    

    然后,在您的 App.js 中,您可以使用

    访问它
    props.location.state.detail
    

    这可能需要您使用 withRouter 作为 HOC。我要改变的一件事是在 componentDidMount 中获取您的 api。然而,如果你用钩子来做这件事会容易得多。虽然它可能需要一些重构,但您可以使用钩子进行 api 调用,这样启动和运行起来要简单得多。

    【讨论】:

    • 我试过了,它只会显示一个空的结果页面。但是在 app.js 中它会显示结果。那么我如何才能获取这些值以显示在 result.js 中呢?
    • 这可能需要使用 withRouter。
    • 在你的结果中抛出一个 console.log(props) 以便我们知道我们在寻找什么
    猜你喜欢
    • 2017-06-26
    • 1970-01-01
    • 2017-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-13
    • 2013-06-14
    相关资源
    最近更新 更多