【问题标题】:How to pass props or state or even parameter to a component in typescript react如何将道具或状态甚至参数传递给打字稿反应中的组件
【发布时间】:2021-11-07 14:20:04
【问题描述】:

这里是超级菜鸟...

所以,我有这个学校项目,但事情变得有点困难......

我正在尝试将一些道具从一个组件传递到另一个组件,但我不知道为什么它总是失败。

因此,这个想法是,当有人从一个组件中选择一个选项时,用户将被重定向到具有该选择的 ID 或编号的另一个页面,因此某些内容将从数据库中提取并呈现在屏幕上.

重定向部分似乎是简单的部分。这是代码:

{this.state.selectedCityCode > 0 && (
      <Redirect
        to={{
          pathname: `/deals/${this.state.selectedCityCode}/${this.state.selectedCityName}`,
          state: {
            cityCode: this.state.selectedCityCode,
            cityName: this.state.selectedCityName
          }
        }}
      />
    )}

现在,重定向按预期工作,url 发生变化,新组件 ger 呈现错误,因为 ID 没有传递,或者目标组件没有得到它。

在路由器组件中,这是重定向的相关部分:

<Route exact path="/deals/:cityCode/:cityName" component={AllDeals}></Route>

在目标组件中,这是相关部分——据我所知——

interface AllDealsProps {
          cityCode: number;
          cityName: string;
}

还有这个:

public componentDidMount = async () => {
const response = await axios.get<Deal[]>( http://localhost/destinations/${this.props.cityCode}/all );
this.setState({ deals: response.data }); };

我用过:

import { useParams } from "react-router-dom";

并尝试这样做:

  public componentDidMount = async () => {
    const params = useParams();
    const response = await axios.get<Deal[]>(
      `http://localhost:4000/destinations/${this.props.cityCode}/deals`
    );

    this.setState({ deals: response.data });
  };

问题是,“cityCode”和“cityName”永远不会被拾取并且永远是未定义的。

我看到了一些关于使用的东西:

this.props.location.state.cityCode

但它总是会说“'Readonly & Readonly'.ts(2339) 类型上不存在属性 'location'”

【问题讨论】:

    标签: typescript react-typescript react-tsx


    【解决方案1】:
    import { useEffect, useState } from 'react';
    import { useParams } from 'react-router';
    
    function Sample() {
        const params = useParams();
    
        // data will hold the value
        const [data, setData] = useState([]);
        const { cityCode, cityName } = params;
    
        useEffect(() => {
            const response = await axios.get<Deal[]>(
                `http://localhost/destinations/${cityCode}/${cityName}/all`,
            );
            setData([...response.data]);
        },[]);
    }
    
    export default Sample();
    
    

    【讨论】:

    • 感谢您的回复。我收到此错误:Line 8:16: React Hook "useParams" cannot be called at the top level. React Hooks must be called in a React function component or a custom React Hook function react-hooks/rules-of-hooks
    • @AhmadDakhlallah,你能告诉我们你是如何调用 useParams() 的吗??
    • public componentDidMount = async () => { const params = useParams();常量响应 = 等待 axios.get(http://localhost:4000/destinations/${this.props.cityCode}/deals); this.setState({ 交易:response.data }); };
    • @AhmadDakhlallah,你能更新你的问题并添加组件的整个代码吗?
    • 完成。请检查。
    猜你喜欢
    • 2021-11-10
    • 2017-09-23
    • 2019-01-27
    • 2021-03-02
    • 2021-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-07
    相关资源
    最近更新 更多