【问题标题】:React-rating-rating-stars-component value dose not changeReact-rating-rating-stars-component 值不变
【发布时间】:2021-08-23 14:41:52
【问题描述】:

我正在使用 react-rating-starts-component 并且我已经在使用 .map 的卡片中多次使用它,它工作正常。但是,当我将它添加到一个页面时,我给它的初始值是 0 并且它不会从该值更改我使用后端在 componentdidmount() 中更新它的值,在控制台中它给我 5 但它显示 0

获取星星并查看星星的函数

function getstars(props){
  return(
    <ReactStars 
    value={props.Rating}
    count={5}
    size={25}
    edit={false}
    isHalf={false}
    activeColor="#ffea00"
/> 
  )
}

来自componentdidmount的SetState

this.setState({
        info: resp.data.PlaceInformation,
          id: resp.data.PlaceInformation._id,
          Name: resp.data.PlaceInformation.Name,
          Description: resp.data.PlaceInformation.Description,
          Phone: resp.data.PlaceInformation.Phone,
          Website: resp.data.PlaceInformation.Website,
          Instagram: resp.data.PlaceInformation.Instgram,
          Twitter: resp.data.PlaceInformation.Twitter,
          Rating: resp.data.PlaceInformation.Rating,
          PRating: resp.data.PlaceInformation.PRating,
          OpenTime: resp.data.PlaceInformation.OpenTime,
          CloseTime: resp.data.PlaceInformation.CloseTime,
          Image: resp.data.PlaceInformation.icon,
          Photos: resp.data.PlaceInformation.photos,
          GoogleMap: resp.data.PlaceLocation.GoogleMap,
          City: resp.data.PlaceLocation.City,
          Street: resp.data.PlaceLocation.Street,
          ZibCode: resp.data.PlaceLocation.ZibCode,
          Reviews: resp.data.PlaceReviews,
  })

在反应渲染中

<div>{getstars(this.state.Rating)}</div>

Rating 的初始值为“0”,在开始时不会改变,但在控制台会改变。 当我更改评级的初始值时,它会更改。 感谢您帮助我并考虑到它:)

【问题讨论】:

  • 你能创建一个像this 这样的沙箱来重现你的问题吗?顺便说一句,您好像忘记实现 onChange 属性了。

标签: javascript node.js reactjs react-router


【解决方案1】:

我认为你需要检查你的论点。 在 getStars 函数中,您传递的是 this.state.Rating 对象而不是整个状态,所以当您在内部使用它时,我想您应该直接使用它,而不是从道具中获取它。

<div>{getstars(this.state.Rating)}</div> 
//You passed the whole Rating object here

代码应该是

function getstars(Rating){
  return(
    <ReactStars 
    value={Rating}
    count={5}
    size={25}
    edit={false}
    isHalf={false}
    activeColor="#ffea00"
/> 
  )
}

或者,您可以更改传递方式并使用对象字面量传递它,以便您可以在 props 参数中获取 Rating

<div>{getstars({Rating: this.state.Rating } )}</div> 
//Here you wrap the Rating with object literal 
//so that in the function you can fetch it from props argument

那么就不需要改变你的getStars函数了。

【讨论】:

  • 你能检查一下你的 resp.data.PlaceInformation.Rating 是否有数据。如果你能给我一个代码框,那对我帮助你调试真的很有帮助。您可以尝试将 console.log 并在 function getstars 中查看参数。
猜你喜欢
  • 1970-01-01
  • 2020-12-06
  • 1970-01-01
  • 2023-02-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多