如何知道某个反应链接组件已被点击 [英] How to know a react link component has been clicked
本文介绍了如何知道某个反应链接组件已被点击的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当组件中的<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( ... )
}
}
推荐答案
我认为您有几个选项可以有条件地处理仅在通过链接访问组件时调用getData
。
使用某些本地状态保存链接的反应键值,并将其作为要在路由组件中检查的路由状态发送。
示例:
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(); } }
- 优点:不重新挂载目标布线组件。不会将重复路径推送到历史记录中。
- 缺点:添加更多移动部分,即本地状态和更新器。
将
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
个组件。将每个新实例&q;推入历史记录堆栈。
这篇关于如何知道某个反应链接组件已被点击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文