首页 > 解决方案 > React Router - 如何在页面刷新时执行onclick?

问题描述

你们所有的编码专家都可以帮我解决这个问题吗?

代码如下所示。

我正在尝试实现一个简单的搜索页面。您将被重定向到此页面,该页面包含您在上一页中输入的搜索条件的答案。在当前页面中,您还可以通过输入新的搜索条件来修改您得到的答案,然后单击搜索以获取新的答案,替换旧的答案。理想情况下,在输入新的搜索条件时,应该在页面的url中替换旧的querystring,然后页面会刷新,然后用新的querystring得到新的答案,在刷新的页面中显示. 所以这就是我写的。

import React from 'react';
import { Link } from 'react-router-dom';
const querystring = require('querystring');

class SearchResult extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            answer: '',
            input: '',
        };
        this.getEntries = this.getEntries.bind(this);
        this.updateRes = this.updateRes.bind(this);
        this.handleDetailChange = this.handleDetailChange.bind(this);
    }

    componentDidMount() {
        this.updateRes();
    }

    getEntries = async () => {
        this.setState({
            loading: true,
        });

        const response = await fetch(
            this.props.location.pathname + this.props.location.search 
        );
        const body = await response.json();

        return body;
    };

    updateRes = async () => {
        this.getEntries()
            .then((resolve) =>
                this.setState({
                    answer: resolve.answer,
                })
            )
            .catch((err) => console.log(err));
    };

    handleInputChange(event) {
        this.setState({
            input: event.target.value,
        });
    }

    render() {
        let currentPath = this.props.location.pathname;
        let qString = querystring.stringify(this.state.input);

        return (
            <div id='result-page'>
                <div>This is the answer : {this.state.answer}</div>

                <label htmlFor='input'>Input here:</label>

                <input type='text' name={'input'} onChange={this.handleInputChange} />

                <Link to={`${currentPath}?${qString}`} onClick={this.updateRes}>
                    <button> Search </button>
                </Link>
            </div>
        );
    }
}

export default SearchResult;

它所做的不是我所期望的。当我点击搜索时,我得到的答案是基于上一页的条件/查询字符串(不是我刚刚输入的新的)。这可能是因为在用新的查询字符串更新查询字符串之前执行了onClickof <Link/>,这不是我想要的!如何在通过链接更改和刷新 url 后执行 OnClick 处理程序?

标签: reactjsreact-router

解决方案


通常该方案如下所示(剧透 - 应使用路线):

  1. 单击链接更改路径。
  2. 根据路径中发送的参数路由发送 axios 请求并显示“正在加载..”
  3. 当收到来自服务器的响应时,表示组件的数据将被更新。即使用户在不访问搜索页面的情况下打开链接“http:\yourapp.com\what-is-the-highest-mountain-in-the-world”,这也将起作用

推荐阅读