简体   繁体   English

在 React 中将数据从一个组件传递到另一个组件的问题

[英]Problem with passing data from one component to another in React

I have a SearchForm component in the header where I fetch data from my API and get the data for my search and I need to use search in my software component to display the software I found.我在 header 中有一个 SearchForm 组件,我从我的 API 获取数据并获取我的搜索数据,我需要在我的软件组件中使用搜索来显示我找到的软件。

SearchForm component: SearchForm 组件:

const SearchForm = ({ style }) => {

  const [search, setSearch] = useState('');
  const [shouldFetch, setShouldFetch] = useState(false);

  const handleChange = (e) => {
    setSearch(e.target.value);
  }

  useEffect(() => 

    if (shouldFetch) {

      (async () => {

        const response = await fetch(`http://127.0.0.1:8000/api/software/?search=${search}`);

        const data = await response.json();

        setShouldFetch(false);

      })()

    }

  }, [shouldFetch]);

  const handleClick = () => setShouldFetch(true);

  return (
    <div
      className={styles["search-form"]}
      id={styles["search-form"]}
      style={style}
    >
      <form onKeyDown={OnKeyDown(handleClick)}>
        <input
          type="text"
          placeholder="Enter something..."
          autoComplete="off"
          maxLength="30"
          onChange={handleChange}
        />
        <SearchButton onClick={handleClick} />
        <small>ENTER</small>
      </form>
    </div>
  );
};

export const SearchButton = ({ style, id, onClick }) => {
  return (
    <button
      type="button"
      style={style}
      id={id}
      onClick={onClick}
    >
      <FontAwesomeIcon icon={faSearch} />
    </button>
  );
};

And Softwares component:和软件组件:

const Softwares = () => {

  const [softwares, setSoftwares] = useState([]);
  const [total, setTotal] = useState(null);
  const [totalPages, setTotalPages] = useState(null);
  const [valid, setValid] = useState(false);

  const fetchData = async ({ currentPage }) => {

    const response = await fetch(`http://127.0.0.1:8000/api/software/?p=${currentPage}`);

    const data = await response.json();

    setSoftwares(data.results);
    setTotal(data.count);
    setTotalPages(data.total_pages);
    setValid(true);

  }

  useEffect(() => {
    fetchData({ currentPage: 1 });
  }, []);

  return (
    <>
    {
      valid &&
      <section className={styles.softwares}>
        ...
        {softwares.map(s => (
          <Article key={s.id} pathname={s.id} title={s.title} image={s.image} pubdate={s.pub_date} icon={s.category.parent.img} categoryID={s.category.id} categoryName={s.category.name} dCount={s.counter} content={s.content} />
        ))}
        <Paginator totalPages={totalPages} total={total} onMovePage={fetchData} />
      </section>
    }
    </>
  );
};

I can't use SearchForm in Softwares because in App.js they are "quite distant", I just wouldn't want to turn it all into one component.我不能在软件中使用 SearchForm,因为在 App.js 中它们“相当遥远”,我只是不想把它全部变成一个组件。

Here's how it look like in App.js:下面是它在 App.js 中的样子:

const App = () => {

    ...

    return (

        ...

        <Header />

    <div className="container">
      <div className="row">
        <div id="content" className="left">
          <div className="inner">
            <Switch>
              <Route path="/" exact component={Softwares} />
              <Route path="/software/:id" exact component={SoftwareDetail} />
              <Route path="/category/:id" exact component={CategoryDetail} />
            </Switch>
                    </div>
                </div>
            </div>
        </div>
        
        ...

    );
}

So what should I do?所以我该怎么做?

Actually its a valid approach to move the shared state one component up, its called lifting state, here is the official reference https://reactjs.org/docs/lifting-state-up.html Actually its a valid approach to move the shared state one component up, its called lifting state, here is the official reference https://reactjs.org/docs/lifting-state-up.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM