【问题标题】:How to know a react link component has been clicked如何知道一个反应链接组件已被点击
【发布时间】:2021-11-02 06:39:20
【问题描述】:

如何在组件中单击<Link> 时捕获?第一次单击链接时,页面加载正常。但是,当您再次单击同一链接时,它不会重新加载数据。这是标准结果,因为它仅在状态/道具发生变化时重新渲染,但我想在重新访问页面时从服务器重新加载新数据。

我尝试过使用componentDidUpdate,但这只会以无限循环结束。我正在寻找一种方法来了解何时使用 react-router-dom 并查询服务器以获取新数据。

我列出了下面使用的分解代码片段。

<Switch>
    <Route path="/users" component={Users}/>
</Switch>
<Link to={"/users"}>Users</Link>
class Users extends Component {
    componentDidMount() {
        this.getData();
        console.log('componentDidMount');
    }

    componentDidUpdate(nextProps, nextState) {
        console.log('componentDidUpdate');
    }
    getData() {
        axios.get(this.props.table.url).then(response => {
            this.setState({ users: response.data, loading: false})
        })
    }

    render() {
        return( ... )
    }
}

【问题讨论】:

  • 当您按下Link按钮时,路由已更改为“用户”,每次更改路由时,componentDidMount都会调用。如果它不适用于您的应用程序,我建议您创建一个代码框。
  • 另外一个问题,Link按钮在另一个页面(路由)上,所以当你点击它时,路由已经变成/user所以怎么才能第二次点击Link ? user 页面上有吗?

标签: reactjs react-router react-router-dom


【解决方案1】:

我认为您有几个选项可以“有条件地”处理调用 getData 仅在通过链接访问组件时。

  1. 使用一些本地状态来保存链接的 React 键值,并作为路由状态发送以在路由组件中进行检查。

    例子:

    import { v4 as uuidV4 } from "uuid";
    
    ...
    
    const [linkKey, setLinkKey] = useState(uuidV4());
    
    ...
    
    <Link
      key={linkKey}
      to={{ pathname: "/users", state: { key: linkKey } }}
      onClick={() => setLinkKey(uuidV4())}
    >
      Users
    </Link>
    

    用户

    componentDidUpdate(prevProps, prevState) {
      if (prevProps.location.state?.key !== this.props.location.state?.key) {
        this.getData();
      }
    }
    
    • 优点:不重新安装目标路由组件。不会将重复的路径推送到历史记录中。
    • 缺点:添加了更多移动部分,即本地状态和更新程序。
  2. 使用Redirect 从带有“随机”路径参数的路径到“/users”路径。

    import { v4 as uuidV4 } from "uuid";
    
    ...
    
    <Link to={generatePath("/users/:key", { key: uuidV4() })}>Users</Link>
    
    ...
    
    <Switch>
      <Redirect from="/users/:key" to="/users" />
      <Route path="/users" component={Users} />
    </Switch>
    
    • 优点:活动部件更少。
    • 缺点:每次都重新安装Users 组件。将每个新“实例”推入历史堆栈。

【讨论】:

  • 我最终使用+ new Date() 来识别新的点击,这似乎比导入另一个库的开销更少。您是否建议有理由在时间戳上使用 uuid?
  • @Bradmage 不是一个强有力的理由。 GUID (uuid) 将保证唯一性,但时间戳可能足够独特,足以满足您的需求。我参与的很多项目已经使用uuid,所以很容易转到。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-05-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多