簡體   English   中英

如何正確使用帶有 React 功能組件的鍵? 這是我的喜歡按鈕:

[英]How do I properly use keys with React functional components? Here's my like button:

我正在嘗試使用 React 構建一個類似 Facebook 的按鈕,以便更好地處理有狀態組件。 我不確定問題是什么,但我認為這是關鍵。

Error: Objects are not valid as a React child (found: object with keys {numLikes, onSelect}). If you meant to render a collection of children, use an array instead.
    in p (at LikeButton.js:8)
    in LikeButton (at App.js:10)
    in App (at src/index.js:9)
    in StrictMode (at src/index.js:8)

這是 App.js:

import React, { useState } from 'react';
import './App.css';
import LikeButton from './components/LikeButton';

function App() {
  const [likes, updateLikes] = useState(23);
  const [liked, updateLiked] = useState(false);

  return (
    <LikeButton 
    secret='like-button'
    numLikes={likes}
    // status={liked}
    onSelect={(liked) => {
      if (liked) {
        updateLikes(likes + 1);
       } else { updateLikes(likes - 1)
       };
      updateLiked(!liked);
      }
    }
    />
    // onClick function here, or in LikeButton.js?
  );
}

export default App;

這是 LikeButton.js:

import React from 'react';
import FaThumbsUp from 'react-icons/fa';

export default function LikeButton(secret, numLikes, onSelect) {
    return (
      <>
        <div key={secret} onClick={onSelect}>Like Button</div>
        <p>{numLikes}</p>
      </>
    );
}

在功能組件中使用屬性時,您需要破壞道具,而不是單獨使用它們。 因為組件的屬性是 function 中的第一個參數

import React from 'react';
import FaThumbsUp from 'react-icons/fa';

export default function LikeButton({secret, numLikes, onSelect}) {
    return (
      <>
        <div key={secret} onClick={() => onSelect(true)}>Like Button</div>
        <div key={secret} onClick={() => onSelect(false)}>Dislike Button</div>
        <p>{numLikes}</p>
      </>
    );
}

當您收到此類錯誤時,請知道您正在嘗試呈現不是 React 元素或非對象類型數據的屬性或變量。

secret、numLikes、onSelect 在道具 object 內。 你應該在使用前銷毀。

const {secret, numLikes, onSelect} = props

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM