在循环 material-ui 评级组件时,'index' 的值在 'onChange' 中保持为 0

时间:2021-08-01 17:17:26

标签: javascript arrays reactjs material-ui

我正在尝试在我的电子商务 react-js Web 应用程序中显示每个产品的评分值。我能够通过 JS 地图功能跟踪/处理哪个产品悬停在它的索引中。 ('onChangeActive' 是这个的处理程序)

 {products.map((product, index) => (

尽管,“onChange”始终为“index”函数参数发送 0,即使我单击数组列表中任何产品的星星也是如此。结果,我无法提供星级功能

    <Rating
    name="hover-feedback"
    value={this.state.rateValue[index] === undefined ?
        product.rating_sum: this.state.rateValue[index]}
    precision={0.5}
    onChange={(event, newValue) => { // OnClick handler
        this.setValue(newValue, index);
    }}
    onChangeActive={(event, newValue) => { // onHover handler
        this.setHover(newValue, index);
    }}
/>
{this.state.rateHover[index] !== undefined && <Box ml={2}>
    {labels[this.state.rateHover[index] !== undefined ?
                                                              this.state.rateHover[index] : this.state.rateValue[index]]}</Box>}

setValue 函数

    setValue = (newValue, index) =>{

    console.log("value", index, newValue)

    if(newValue !== -1 && newValue!== null) {
        let oldValue = this.state.rateValue;
        oldValue[index] = newValue;

        this.setState({
                rateValue: oldValue,

        })
    }
}

1 个答案:

答案 0 :(得分:1)

您应该使用 React useState,而不是尝试使用自定义状态定义重新发明轮子。 https://reactjs.org/docs/hooks-state.html

// Get a hook function
const {
  useState
} = React;

const Example = ({
  title
}) => {
  const [state, setState] = useState({
    rateValue: [0, 0, 0, 0, 0]
  });

  const products = [{
      rating_sum: 4
    },
    {
      rating_sum: 6
    },
    {
      rating_sum: 5
    },
  ]

  const setValue = (event, index) => {

    const newValue = event.target.value

    console.log("value", index, newValue)

    if (newValue !== -1 && newValue !== null) {
      const {
        rateValue
      } = state
      setState({
        rateValue: [
          ...rateValue.slice(0, index), newValue, ...rateValue.slice(index + 1)
        ]
      })
    }
  }
  return ( <
    div > {
      products.map((product, index) => {
        return <div >
          <
          input value = {
            index
          }
        type = 'number'
        onChange = {
          (event, newValue) => {
            setValue(event, index)
          }
        }
        /> < /
        div >
      })
    } < div > {
      state.rateValue
    } < /div>< /
    div >
  );
};

// Render it
ReactDOM.render( <
  Example title = "Example using Hooks:" / > ,
  document.getElementById("react")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<div id="react"></div>