【问题标题】:How to change state through react-router-dom Link?如何通过 react-router-dom 链接改变状态?
【发布时间】:2021-05-17 14:40:48
【问题描述】:

单击图像时,我试图通过链接组件更改状态。我不确定是 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?

【问题讨论】:

  • 在使用useContextredux 之前,不要存储状态值。每次导航时,状态值都会重置为默认值,例如您的 useState(true)

标签: javascript reactjs react-hooks react-link


【解决方案1】:

建议在&lt;Link /&gt; 组件本身上使用 onClick 处理程序:

&lt;Link to={{pathname:'/recipepage', state: {strMeal: strMeal} }} onClick={(e) =&gt; clickHandler(e)}>

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

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

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

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

【讨论】:

  • 我正在尝试打开一个页面,该页面根据我单击的图像显示食谱信息。我已经准备好获取 API。我想将配方的名称发送到链接组件,以便我可以尝试让页面显示信息。
  • 谢谢,但我仍然遇到最初的问题!
  • 在该组件中使用道具做必要的事情。
猜你喜欢
  • 1970-01-01
  • 2021-05-16
  • 2017-05-18
  • 2020-11-30
  • 2021-01-09
  • 2020-09-10
  • 2021-12-28
  • 2020-03-30
  • 2020-07-11
相关资源
最近更新 更多