如何在组件之间传递获取的数据?

How can I pass fetched data between components?

我正在我的 App 组件中获取一些数据并通过它映射以显示名称。我还有一个计数器组件,除了计数之外,我还想从应用程序中获取的数据中呈现用户名。我想知道如何将数据的用户名作为道具传递给计数器组件,以便它也在那里显示名称?

这是我的应用程序:

function App() {
  const {data, isLoading} = useAsync({promiseFn: loadUsers})
  if (isLoading)
    return "Loading..."
  if (data)

    return (<div className="container">
      {
        data.map(user => (
          <div key={user.username} className="row">
            <div class="col-md-8">
              <div class="card-body">
                <h2>{user.name}</h2>  // Need this to also display in button component
                <Counter id={user.name}/>
              </div>

我的计数器组件的 return :

  return (
    <div>
      <b>Would you like to work with (user.name data from app) </b> &nbsp; <i onClick={handleIncrement} class="far fa-thumbs-up" style={clickStyle}> Yes!</i>
      <br/>
      <h><b>{count}</b> have said Yes!</h>
    </div>
  );
}

在您的 App 组件中,您将用户名作为 id 发送到 Counter。当您将变量从父组件发送到另一个组件时,您可以通过 props 在子组件中。您还需要将道具传递给子组件。此外,您应该将 user.name 更改为 props.id。根据您在 stackbiltz 中附加的代码。这是正确的代码:

function Likes(props) {
  const [count, setCount] = useState(0);
  const KEY = `count-${props.id}`;
  const clickStyle = {
    color: '#2197ba',
    cursor: 'pointer'
  };

  useEffect(() => {
    const parsedCount = Number(localStorage.getItem(KEY) || 0);
    setCount(parsedCount);
  }, []);

  useEffect(() => {
    localStorage.setItem(KEY, count);
  }, [count]);

  const handleIncrement = () => {
    setCount(prevCount => prevCount + 1);
  };

  return (
    <div>
      <b>Would you like to work with counter {props.id} </b> &nbsp;{' '}
      <i onClick={handleIncrement} class="far fa-thumbs-up" style={clickStyle}>
        {' '}
        Yes!
      </i>
      <br />
      <h>
        <b>{count}</b> have said Yes!
      </h>
    </div>
  );
}

有关道具的更多信息,请参阅此文档:https://reactjs.org/docs/components-and-props.html

你也可以解构你的 props inside Counter 组件,这样你就不需要写 props.id.

function Counter({id}) {  //here I destructured it
      return (
        <div>
          <b>Would you like to work with {id} data from app </b> &nbsp; <i onClick={handleIncrement} class="far fa-thumbs-up" style={clickStyle}> Yes!</i>
          <br/>
          <h><b>{count}</b> have said Yes!</h>
        </div>
      );
    }