向功能组件添加反应道具

时间:2019-11-13 07:40:54

标签: javascript reactjs

我有一些来自API的数据,希望在另一个无状态功能组件中显示。

这是状态-const [user, setUser] = useState([]); 这是我想在其他组件中输出的数据:

const getData = async () => {
  const response = await fetch(`https://api.github.com/users/${search}`);
  const data = await response.json();
  setUser(data);
};

我为其他组件尝试的操作是:

const ProfileImg = props => <img src={props.avatar_url} alt="avatar" />; // or props.user.avatar_url

我也尝试过解构,但无法获取数据。


这就是我现在试图传递给其他人的整个表单组件 较小的组件。

import React, { useState } from 'react';
import styled from 'styled-components';

const Form = (props) => {
    const [search, setSearch] = useState('');
    // const [formVal, setForm] = useState('');
    const [user, setUser] = useState([]);

    const updateSearch = e => {
        setSearch(e.target.value);
    }
    const getSearch = e => {
      e.preventDefault();
      getData();
      // setForm(search);
      setSearch('');
    }

    const getData = async () => {
      const response = await fetch(`https://api.github.com/users/${search}`);
      const data = await response.json();
      setUser(data);
      // console.log(data);
    }

    return (
     <React.Fragment>
     <StyledForm onSubmit={getSearch}>
     <input type="text" value={search} onChange={updateSearch} placeholder="Search for a user" />
     </StyledForm>
     <div>
     <h2>{user.followers}</h2>
     </div>
     </React.Fragment>
    );
}

1 个答案:

答案 0 :(得分:-1)

不能完全确定这是否是您想要的,但是请参见下面。您似乎与ProfileImage上的道具很接近,但是需要根据下面的内容进行一些细微改动,以提供正确的头像:

import React, {useState, useEffect} from "react";
import ReactDOM from "react-dom";

import "./styles.css";

const ProfileImg = props => <img src={props.user.avatar_url} alt="avatar" />;

function App() {
  const [user, setUser] = useState([]);

  useEffect(() => {
    const getData = async () => {
      const response = await fetch(`https://api.github.com/users/h3h394`);
      const data = await response.json();
      console.log(data);
      setUser(data);
    };

    getData();
});
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <ProfileImg user={user}/>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);