javascript - 如何通过 react-router-dom 链接改变状态?
问题描述
当我单击图像时,我试图通过链接组件更改状态。我不确定是 Link 组件的编写方式还是clickHandler
使用不正确,但即使在我单击它之后,它也会将状态记录为 true。
import React, {useState, useEffect} from 'react'
import {Link, Switch, Route} from 'react-router-dom'
import RecipePage from './RecipePage'
export default function Recipes({dataArray}){
const [strMeal, setStrMeal] = useState(true)
function clickHandler(){
setStrMeal(false)
}
return(
<div>
<Link to={{pathname:'/recipepage', state: {strMeal: strMeal} }}>
<div onClick={() => clickHandler()}>This is an image</div>
</Link>
</div>
)
}
如何将状态更改为 false?
解决方案
<Link />
建议在组件本身上使用 onClick 处理程序:
<Link to={{pathname:'/recipepage', state: {strMeal: strMeal} }} onClick={(e) => clickHandler(e)}
>
现在,您还需要阻止链接的默认行为:
function clickHandler(e){
e.preventDefault()
setStrMeal(false)
}
但我不确定你为什么要这样做?因为,链接用于转到您提供的路径。所以,我猜你想做点什么/recipepage
:
因此,您将获得路径名,甚至获得您提供的状态,并在组件中对其进行处理。
推荐阅读
- django - Django3.0.1:使用 ForeignKey 后显示此问题 - 此字段不能为空
- python - 如何找到5种不同分类的混淆矩阵?
- c++ - 你能在 C++ 中做一个指向类的指针吗?
- php - 将数组变量转换为关联数组
- python - Scrapy-splash 在“服务器正在侦听 http://0.0.0.0:8050”时没有结果
- java - 而不是类“PlaceLikelihood”
- haskell - 如何导入新类型实例
- http - 如何将 Istio Service Mesh 从 http 升级到 http2?
- amazon-web-services - 在 AWS 中安排资源的自动关闭
- c++ - 是否可以在 C++ 中拥有自动变量的静态部分?