【问题标题】:How to export state in useState hook and use it in other components如何在 useState 钩子中导出状态并在其他组件中使用
【发布时间】:2021-12-31 03:29:11
【问题描述】:

所以我创建了一个movie-db应用程序,我想在Top RatedPopular等不同类别之间切换。我试图通过将状态设置为单击的文本值来做到这一点稍后用于形成要获取的完整 url。

这是我的代码:

App.js

import Movie from "./components/Movie";
import requests from "./components/ApiRequest";
import Navbar from "./components/Navbar";

function App() {

  return (
    <div className="App">
      <Navbar />
      <div className="movie-container">
        <Movie fetchUrl={requests.fetchTrending} />
      </div>
        
    </div>
  );
}

export default App;

Navbar.js

import React, { useState } from 'react'
import SearchBar from './SearchBar'
import { FiFilter } from 'react-icons/fi'
import requests from "../components/ApiRequest";


const Navbar = () => {
    const [category, setCategory] = useState('Trending')

    return (
        <div className="navbar-container">
            <button className="navbar-btn"><FiFilter />Filter</button>
            <div className="categories">
                <button onClick={() => setCategory("Trending")}>Trending</button>
                <button onClick={() => setCategory("Popular")}>Popular</button>
                <button onClick={() => setCategory("TopRated")}>Top Rated</button>
                <button onClick={() => setCategory("Upcoming")}>Upcoming</button>
            </div>
            <SearchBar />
        </div>
    )   
}

所以我想在函数外部从Navbar.js 获取category 的值并在此处使用它&lt;Movie fetchUrl={requests.fetch{category} /&gt;,以便我可以从请求中获取该url

【问题讨论】:

标签: reactjs use-state


【解决方案1】:

您应该将状态提升到一个共同的祖先,即App 在这种情况下,它可以作为道具传递给子组件。

例子:

function App() {
  const [category, setCategory] = useState('Trending');

  return (
    <div className="App">
      <Navbar setCategory={setCategory}/>
      <div className="movie-container">
        <Movie fetchUrl={requests.fetchTrending(category)} />
      </div>
        
    </div>
  );
}

...

const Navbar = ({ setCategory }) => {
  return (
    <div className="navbar-container">
      <button className="navbar-btn"><FiFilter />Filter</button>
      <div className="categories">
        <button onClick={() => setCategory("Trending")}>Trending</button>
        <button onClick={() => setCategory("Popular")}>Popular</button>
        <button onClick={() => setCategory("TopRated")}>Top Rated</button>
        <button onClick={() => setCategory("Upcoming")}>Upcoming</button>
      </div>
      <SearchBar />
    </div>
  )   
}

【讨论】:

    【解决方案2】:

    你需要提升你的状态。这意味着您的 useState 'category' 钩子必须在父组件中,它可以将此数据作为道具传递给子组件。在您的情况下,电影组件的父组件是 App 组件,因此 App 组件必须包含

    const [category, setCategory] = useState('Trending')
    

    现在您可以将 'category' 属性传递给 Movie 组件,并将 setCategory 传递给 Navbar 组件

    【讨论】:

      猜你喜欢
      • 2019-08-23
      • 2023-03-14
      • 2020-11-30
      • 2020-02-12
      • 2023-01-04
      • 2021-10-02
      • 1970-01-01
      • 2019-04-26
      • 1970-01-01
      相关资源
      最近更新 更多