传递属性给函数组件

huangapple go评论73阅读模式
英文:

passing props to functional component

问题

以下是您要翻译的代码部分:

我无法将任何props从父组件传递给我的函数组件我从查询字符串参数或Cookie中获取值然后将其传递但在我的非常基本的用例中似乎不起作用我的父组件是

import React, { useState, useEffect } from 'react';
import './App.css';
import { Helmet } from 'react-helmet';
import Cookies from "universal-cookie";
import Navbar from './components/Navbar';
import Footer from './components/Footer';
import Home from './components/Home';
import { IBookmaker } from './interfaces/IBookmaker';

function App() {
    const cookies = new Cookies();
    const query = new URLSearchParams(window.location.search)
    var bookmakerid = Number(query.get('bid'));
    if (bookmakerid && bookmakerid > 0) {
        cookies.set("bid", bookmakerid)
    }
    else {
        if (cookies.get('bid') && Number(cookies.get('bid')) > 0) {
            bookmakerid = Number(cookies.get('bid'));
        }
    }

return (
         <div className="App">           
            <Helmet>

            </Helmet>
            <Navbar ></Navbar>
            <div className="page bg-gray-100">
                <section className="section section-variant-1 bg-gray-100">
                     <Home bookmakerid={bookmakerid} />
                </section>
            </div>
            <Footer />
        </div>
     );
}

我的子组件"Home"如下

import React, { useEffect, useState, } from 'react';
import "../App.css";
import { ICompetition } from '../interfaces/ICompetition';

function Home({ bookmakerid }) {
    const [compList, setData] = useState<ICompetition | null>(null);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);

    useEffect(() => {
        fetch("http://localhost:5242/GetCompetitions?bid=" + bookmakerid, { method: "GET" })
            .then(response => {
                if (response.ok) {
                    console.log(response);
                    //return response.json();
                }
            })
            //.then(data => {
            //    setData(data);
            //})
            //.catch(err => {
            //    setError(err)
            //});
    }, []);

    return (
        <section className="section section-variant-1 bg-gray-100">
            <div className="isotope-item" data-filter="football">
                    <div className="sport-table">
                        <div className="sport-table-tr">
                            <div id="runnerContainer" className="carousel-inner">                            
                        </div>
                    </div>
                </div>
            </div>
        </section>
);
}

希望这对您有所帮助!如果您需要进一步的帮助,请随时提出。

英文:

i can't seem to pass any props from my parent to my functional component. I get the value from a query string parameter or cookie then just pass it through but it dosen't seem to work in my very basic use case. My parent is

import React, { useState, useEffect } from &#39;react&#39;;
import &#39;./App.css&#39;;
import { Helmet } from &#39;react-helmet&#39;;
import Cookies from &quot;universal-cookie&quot;;
import Navbar from &#39;./components/Navbar&#39;;
import Footer from &#39;./components/Footer&#39;;
import Home from &#39;./components/Home&#39;;
import { IBookmaker } from &#39;./interfaces/IBookmaker&#39;;
function App() {
const cookies = new Cookies();
const query = new URLSearchParams(window.location.search)
var bookmakerid = Number(query.get(&#39;bid&#39;));
if (bookmakerid &amp;&amp; bookmakerid &gt; 0) {
cookies.set(&quot;bid&quot;, bookmakerid)
}
else {
if (cookies.get(&#39;bid&#39;) &amp;&amp; Number(cookies.get(&#39;bid&#39;)) &gt; 0) {
bookmakerid = Number(cookies.get(&#39;bid&#39;));
}
}    
return (
&lt;div className=&quot;App&quot;&gt;           
&lt;Helmet&gt;
&lt;/Helmet&gt;
&lt;Navbar &gt;&lt;/Navbar&gt;
&lt;div className=&quot;page bg-gray-100&quot;&gt;
&lt;section className=&quot;section section-variant-1 bg-gray-100&quot;&gt;
&lt;Home bookmakerid={bookmakerid} /&gt;
&lt;/section&gt;
&lt;/div&gt;
&lt;Footer /&gt;
&lt;/div&gt;
);
}

My child "Home" component is

import React, { useEffect, useState, } from &#39;react&#39;;
import &quot;../App.css&quot;;
import { ICompetition } from &#39;../interfaces/ICompetition&#39;;
function Home({ bookmakerid }) {
const [compList, setData] = useState&lt;ICompetition | null&gt;(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() =&gt; {
fetch(&quot;http://localhost:5242/GetCompetitions?bid=&quot; + bookmakerid, { method: &quot;GET&quot; })
.then(response =&gt; {
if (response.ok) {
console.log(response);
//return response.json();
}
})
//.then(data =&gt; {
//    setData(data);
//})
//.catch(err =&gt; {
//    setError(err)
//});
}, []);
return (
&lt;section className=&quot;section section-variant-1 bg-gray-100&quot;&gt;
&lt;div className=&quot;isotope-item&quot; data-filter=&quot;football&quot;&gt;
&lt;div className=&quot;sport-table&quot;&gt;
&lt;div className=&quot;sport-table-tr&quot;&gt;
&lt;div id=&quot;runnerContainer&quot; className=&quot;carousel-inner&quot;&gt;                            
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/section&gt;
);
}

If there is a querystring/cookie value it does populate the bookmakerid but in home i always get "Binding element 'bookmakerid' implicitly has an 'any' type."

Also if i try to define my Home component with props function Home(props) { (to try props.bookmakerid) I get Binding element 'props' implicitly has an 'any' type.

Every example i look at online it just seems to work in a very similar way that i'm attempting it here. This video for example https://www.youtube.com/watch?v=kHJSNFU7H4U&amp;t=580s. Just can't see how my code is different. I'm using Visual studio 2022 with the standard react typescript template. Thanks.

答案1

得分: 1

以下是代码部分的中文翻译:

由于您正在使用 TypeScript,您需要声明参数的类型,即在这种情况下是 props,否则您将会遇到这种类型的错误。

查看 App 的代码,bookmakerId 似乎是一个数字,所以这应该可以解决问题:

import React, { useEffect, useState } from 'react';
import "../App.css";
import { ICompetition } from '../interfaces/ICompetition';

interface HomeProps {
    bookmakerid: number;
}

function Home({ bookmakerid }: HomeProps) {
    const [compList, setData] = useState<ICompetition | null>(null);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);

    useEffect(() => {
        fetch("http://localhost:5242/GetCompetitions?bid=" + bookmakerid, { method: "GET" })
            .then(response => {
                if (response.ok) {
                    console.log(response);
                    //return response.json();
                }
            })
            //.then(data => {
            //    setData(data);
            //})
            //.catch(err => {
            //    setError(err)
            //});
    }, []);

    return (
        <section className="section section-variant-1 bg-gray-100">
            <div className="isotope-item" data-filter="football">
                <div className="sport-table">
                    <div className="sport-table-tr">
                        <div id="runnerContainer" className="carousel-inner">                            
                        </div>
                    </div>
                </div>
            </div>
        </section>
    );
}

请注意,您将这个数字连接到 fetch URL 中,这不是纯粹的字符串,因为字符串 + 数字会导致数字隐式转换为字符串,但这应该能正常工作。如果您想要确保,您可以考虑显式转换,或者更好的做法可能是将 bookmakerid 视为字符串,因为您可能不希望对其进行算术运算。

英文:

As you are using typescript, you need to declare the type of your arguments, the props in this case, otherwise you will get this kind of error.

Looking at the code for App the bookmakerId seems to be a number, so this should do the trick:

import React, { useEffect, useState, } from &#39;react&#39;;
import &quot;../App.css&quot;;
import { ICompetition } from &#39;../interfaces/ICompetition&#39;;
interface HomeProps {
bookmakerid: number;
}
function Home({ bookmakerid }: HomeProps) {
const [compList, setData] = useState&lt;ICompetition | null&gt;(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() =&gt; {
fetch(&quot;http://localhost:5242/GetCompetitions?bid=&quot; + bookmakerid, { method: &quot;GET&quot; })
.then(response =&gt; {
if (response.ok) {
console.log(response);
//return response.json();
}
})
//.then(data =&gt; {
//    setData(data);
//})
//.catch(err =&gt; {
//    setError(err)
//});
}, []);
return (
&lt;section className=&quot;section section-variant-1 bg-gray-100&quot;&gt;
&lt;div className=&quot;isotope-item&quot; data-filter=&quot;football&quot;&gt;
&lt;div className=&quot;sport-table&quot;&gt;
&lt;div className=&quot;sport-table-tr&quot;&gt;
&lt;div id=&quot;runnerContainer&quot; className=&quot;carousel-inner&quot;&gt;                            
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/section&gt;
);
}

Note that you concatenate this number to the fetch URL, that is not exactly pure as string + number means the number is implicitly cast to a string, but it should work. I would consider explicitly casting though if you want to make sure, or probably even better to treat the bookmakerid as a string as you probably do not want to do arithmetic with it.

huangapple
  • 本文由 发表于 2023年3月9日 21:58:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/75685616.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定