在React组件之间共享数据 [英] Sharing data between React components

查看:64
本文介绍了在React组件之间共享数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在React中有一个搜索表单,该表单执行API调用,并使用useState()React挂钩将状态服务器中的数据保存为状态服务器.

I have a search form in React that performs an API call and saves the data called nameservers in-state using the useState() React hook.

我正在尝试确定如何将这些数据传递给另一个组件,以便可以将这些数据用于呈现页面上的其他位置.

I'm trying to determine how I can pass this data to another component so the data can be used for rendering elsewhere on the page.

当前,我只是将数据输出到搜索表下方的返回块中.

Currently, I'm just outputting the data in my return block which appears below the search form.

import React, { useState } from "react";
import { Spinner, Form, Button, Container, Col } from "react-bootstrap";
import { FaSearch } from "react-icons/fa";

const SearchForm: React.FC = () => {
  const [domain, setDomain] = useState("");
  const [loading, setLoading] = useState(false);
  const [nameservers, setNameservers] = useState([]);
  const [submitted, setSubmitted] = useState(false);

  const formText = "Search for a domains";

  const handleChange = (event: any) => {
    setDomain(event.target.value);
  };

  const handleSubmit = (event: any) => {
    event.preventDefault();
    setLoading(true);
    setSubmitted(true);
    console.log(domain);

    fetch(`https://dns.google.com/resolve?name=${domain}&type=NS`)
      .then(results => results.json())
      .then(data => {
        setLoading(false);
        if (data && data.Answer) {
          data.Answer.sort((a: any, b: any) => a.data.localeCompare(b.data));
          setNameservers(data.Answer);
        }
      });
  };

  return (
    <>
      <Form onSubmit={handleSubmit}>
        <Form.Row>
          <Col />
          <Col>
            <Form.Control
              type="text"
              placeholder={formText}
              value={domain}
              onChange={handleChange}
              autoFocus
              required
            />
          </Col>
          <Col>
            <Button variant="primary" type="submit">
              <FaSearch /> Search
            </Button>
          </Col>
        </Form.Row>
      </Form>
      <hr />
      {submitted &&
        nameservers.map((server: any, index: number) => (
          <li key={index}>{server.data}</li>
        ))}

      {submitted && nameservers.length === 0 && <small>Error</small>}

      {loading && (
        <Container className="text-center">
          <Spinner animation="grow" size="sm" />
          <Spinner animation="grow" size="sm" />
          <Spinner animation="grow" size="sm" />
        </Container>
      )}
    </>
  );
};

export default SearchForm;

推荐答案

在组件之间共享数据有多种方法.您可以使用以下选项之一:

There are multiple ways to share data between components. You can use one of the following options:

  • 如果要向其传递数据的组件是 SearchForm 组件的子组件,则可以将其作为 prop 传递.

  • If the component to which you want to pass the data is a child of SearchForm component, then you can pass it as a prop.

如果要通过Redux管理状态,则可以将组件连接到Redux存储,并从组件中的Redux存储中获取所需的数据.

If you are managing state via redux, you can connect components to the redux store and get the required data from the redux store in your components.

您还可以使用React的 Context API 在可能具有父子关系的组件之间共享公共数据.

You can also use React's Context API to share common data between components that may or may not have a parent-child relationship.

如果需要 SearchForm 组件中的数据的组件是 SearchForm 组件的父组件,则可以将回调函数传递给SearchForm 组件作为 prop 组件,并且当 SearchForm 组件中有可用数据时,调用回调函数,以 prop 形式接收,并将数据作为参数传递给该回调函数.

If the component that needs the data from SearchForm component, is a parent component of SearchForm component, you can pass a callback function to the SearchForm component as a prop and when data is available in SearchForm component, call the callback function, received as a prop, and pass the data as an argument to that callback function.

这篇关于在React组件之间共享数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆