首页 > 解决方案 > 如何通过 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?

标签: javascriptreactjsreact-hooksreact-link

解决方案


<Link />建议在组件本身上使用 onClick 处理程序:

<Link to={{pathname:'/recipepage', state: {strMeal: strMeal} }} onClick={(e) => clickHandler(e)}>

现在,您还需要阻止链接的默认行为:

function clickHandler(e){
    e.preventDefault()
    setStrMeal(false)
}

但我不确定你为什么要这样做?因为,链接用于转到您提供的路径。所以,我猜你想做点什么/recipepage

因此,您将获得路径名,甚至获得您提供的状态,并在组件中对其进行处理。


推荐阅读