簡體   English   中英

真正喜歡和不喜歡 Js

[英]like and dislike in reat Js

我使用了material-ui卡片,在這種卡片中,有一個喜歡按鈕,所以我從服務器獲取數據並將它們顯示在卡片上一切都很好,直到現在我只需單擊喜歡按鈕將其中一個添加到我最喜歡的部分但他們都選擇了。

這是我從服務器獲取的卡:

<React.Fragment>
  {advert && advert.map((info, i) =>
    <Grid item xs={4} key={i}>
      <Card className={classes.root} >
        <CardHeader
          title={info.title}
        />
        <CardContent>
          <Typography variant="body2" color="textSecondary" component="p">
            Title: {info.title}
          </Typography>
        </CardContent>
        <CardActions disableSpacing >

          <IconButton aria-label="add to favorites" onClick={() => like(info.id)}>
            {likee ? <FavoriteIconLike /> : <FavoriteIconDislike />}
          </IconButton>

        </CardActions>
      </Card>
    </Grid>
  )}
</React.Fragment>

我寫這樣的函數:

const [likee, setLikee] = React.useState(false)
const like = (id) => {

  let formData = new FormData();
  formData.append('user', sessionStorage.getItem('user'));
  formData.append('code', id);

  axios({
    method: 'post',
    url: `${SERVER_URL}/src/api/like.php`,
    data: formData,
    responseType: 'json',
    config: { headers: { 'Content-Type': 'multipart/form-data' } }
  })
    .then(function (response) {
      //handle success
      console.log(response)
      if (response.data === 'insert') {
        //like discount
        setLikee(true)
      } else if (response.data === 'delete') {
        //dislike
        setLikee(false)
      }

      return response;
    })
    .catch(function (response) {
      //handle error
      console.log(response)

    })
}

當我點擊卡片中的一個喜歡按鈕時,我點擊的卡片正確保存在數據庫中,但在卡片中,每個喜歡按鈕不僅改變了我點擊的那個按鈕。

我給我的卡片拍了一些照片。 第一個是當喜歡按鈕沒有點擊時。

點贊按鈕沒有點擊

第二個鏡頭是當我單擊其中一個時,但所有這些都發生了變化。

當一個類似按鈕被點擊時

和 adver 來自數據庫 ans 是這樣的:

[
    {
        "id": "34",
        "user": "jk.k.kk@gmail.com",
        "price": "78",
        "text": "But when it comes to other components, you may not want to repeat the width and height. In these instances, you can pass children and it will infer its width and height from them. But when it comes to other components, you may not want to repeat the width and height. In these instances, you can pass children and it will infer its width and height from them. But when it comes to other components, you may not want to repeat the width and height. In these instances, you can pass children and it will infer its width and height from them.",
        "url": "..\/public\/uploadPic\/4318b4e04db99f70a9c12cd87b845b641.jpg",
        "token": "fw1kcgkwiwvkerds4faeub13ovli1eis",
        "title": "hall of city",
        "start": "2020-10-03T14:32",
        "expire": "2020-10-29T14:32",
        "code": "erftgyhujk",
        "time": "2020-10-27 16:43:24"
    },
    {
        "id": "32",
        "user": "tytytytyt@gmail.com",
        "price": "45",
        "text": "The data for your components might not be immediately available. You can increase the perceived performance for users by using skeletons. It feels like things are happening immediately, then the information is incrementally displayed on the screen (Cf. Avoid The Spinner).\n\nThe component is designed to be used directly in your components. For instance:",
        "url": "..\/public\/uploadPic\/dd6f5eb18ea833fa1a7aa55f3de097e72.jpg",
        "token": "fw1kcgkwiwvkerds4faeub13ovli1eis",
        "title": "super market",
        "start": "2020-10-05T14:30",
        "expire": "2020-10-29T14:30",
        "code": "rfghnmjkoo",
        "time": "2020-10-27 16:43:35"
    },
    {
        "id": "33",
        "user": "rtrtyhhjhj@gmail.com",
        "price": "67",
        "text": "In addition to accepting width and height props, the component can also infer the dimensions.\n\nIt works well when it comes to typography as its height is set using em units.In addition to accepting width and height props, the component can also infer the dimensions.\n\nIt works well when it comes to typography as its height is set using em units.",
        "url": "..\/public\/uploadPic\/51074e4633a745ac50e3b9943c7970636.jpg",
        "token": "fw1kcgkwiwvkerds4faeub13ovli1eis",
        "title": "AcademyAgri",
        "start": "2020-10-30T14:32",
        "expire": "2020-10-31T14:32",
        "code": "rtbawscbnj",
        "time": "2020-10-27 16:43:39"
    },
    {
        "id": "35",
        "user": "ytytytytyt@gmail.com",
        "price": "45",
        "text": "The icon prop allows you to add an icon to the beginning of the alert component. This will override the default icon for the specified severity.\n\nYou can change the default severity to icon mapping with the `iconMapping` prop. This can be defined globally using theme customization.\n\nSetting the icon prop to false will remove the icon altogether.",
        "url": "..\/public\/uploadPic\/86936421c73e575abbd3ad39a27da1c31.jpg",
        "token": "fw1kcgkwiwvkerds4faeub13ovli1eis",
        "title": "fffflady",
        "start": "2020-10-13T14:22",
        "expire": "2020-10-31T14:22",
        "code": "ujk,powedf",
        "time": "2020-10-27 16:43:47"
    },
    {
        "id": "36",
        "user": "sfsefseefs@gmail.com",
        "price": "90",
        "text": "By default, the skeleton pulsate, but you can change the animation for a wave or disable it entirely.\n\nBy default, the skeleton pulsate, but you can change the animation for a wave or disable it entirely.\n\nBy default, the skeleton pulsate, but you can change the animation for a wave or disable it entirely.\n\nBy default, the skeleton pulsate, but you can change the animation for a wave or disable it entirely.",
        "url": "..\/public\/uploadPic\/f2277a2b2272b8386f266077962340939.jpg",
        "token": "fw1kcgkwiwvkerds4faeub13ovli1eis",
        "title": "sexy fgfg",
        "start": "2020-10-30T16:34",
        "expire": "2020-10-31T16:34",
        "code": "hfE45DAsQf",
        "time": "2020-10-27 16:35:06"
    }
]

很難說,因為您實際上並沒有展示完整的相關代碼(廣告是如何定義的?您在哪里渲染卡片?)但是根據您的代碼,您似乎正在為每個元素渲染卡片一系列廣告。

如果是這種情況,並且渲染該片段的組件是具有likee狀態的組件,那么問題很簡單:渲染每張卡片的組件僅存儲一個應用於每張卡片的likee值。 這意味着,每一個卡的likee值將由所決定likee單卡的價值,哪一個修改父組件。

如果advert包含一組廣告,每個廣告都渲染一張卡片,然后考慮將該卡片抽象為一個單獨的組件,該組件可以包含自己的狀態。 這樣你就可以為每張卡片設置一個單獨的like狀態,存儲它是否被喜歡。

該組件可能如下所示:

const AdvertCard = ({ info }) => {
  const [advertLiked, setAdvertLiked] = useState(false); // Has this advert been liked?
  
  const like =  (id) => {

    let formData = new FormData();
    formData.append('user', sessionStorage.getItem('user'));
    formData.append('code', id);
              
    axios({
      method: 'post',
      url : `${SERVER_URL}/src/api/like.php`,
      data : formData,
      responseType: 'json',
      config : {headers : { 'Content-Type': 'multipart/form-data' }}
    })
      .then(function(response){
        //handle success
        console.log(response);
        if (response.data === 'insert') {
          //like discount
          setAdvertLiked(true);
        } else if(response.data === 'delete') {
          //dislike
          setAdvertLiked(false);
        }
  
        return response;
      })
      .catch(function(response){
        //handle error
        console.log(response);
      })
  }

  return (
    <Card className={classes.root} >
      <CardHeader
        title={info.title}
      />
      <CardContent>
        <Typography variant="body2" color="textSecondary" component="p">
          Title: {info.title}
        </Typography>
      </CardContent>
      <CardActions disableSpacing >

        <IconButton aria-label="add to favorites"onClick={() => like(info.id)}>
          {advertLiked ? <FavoriteIconLike/> : <FavoriteIconDislike />}
        </IconButton>

      </CardActions>
    </Card>
  )
}

隨着組件呈現每個廣告,返回以下內容:

<React.Fragment>
  {advert && advert.map((info, i) => 
    <Grid item xs={4} key={i}>
      <AdvertCard info={info} />
    </Grid>
  )}
</React.Fragment>

另外,請使用比likee更清晰的變量名。 擁有一個狀態、一個likee狀態和一個like函數使得不清楚應該在哪些場景中使用哪個變量/函數,以及每個變量/函數應該如何與另一個具體表現不同。

暫無
暫無

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

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