加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

reactjs – React JS Error:无效尝试去构造非可迭代实例

发布时间:2020-12-15 05:06:46 所属栏目:百科 来源:网络整理
导读:我有一个排序过滤器,它采用一个数组来填充选项.试图看到选项值等于数组中的文本,但我在标题中得到错误: Invalid attempt to destructure non-iterable instance 我需要将文本作为选项标记中的值传递,以便在用户更新过滤器时,正确的文本显示给用户所做的选择
我有一个排序过滤器,它采用一个数组来填充选项.试图看到选项值等于数组中的文本,但我在标题中得到错误:
Invalid attempt to destructure non-iterable instance

我需要将文本作为选项标记中的值传递,以便在用户更新过滤器时,正确的文本显示给用户所做的选择.

这是我的代码:

function Sorting({by,order,rp}: SortingProps) {
    const opts = [
        ['Price (low)','price','asc'],['Price (high)','desc'],['Discount (low)','discount',['Discount (high)',['Most popular','arrival','latest'],['Most recent',];

    const onChange = (i) => {
        const [text,by,order] = opts[i];
        refresh({so: {[by]: order}});
        /* GA TRACKING */
        ga('send','event','My Shop Sort By',text,'Used');
    };

    return (
        <div className={cn(shop.sorting,rp.sorting.fill && shop.sortingFill)}>
            <Select className={shop.sortingSelect} label="Sort By" onChange={onChange} value={`${by}:${order}`}>
                {opts.map(([text],i) =>
                    <Option key={i} value={text}>{text}</Option>
                )}
            </Select>
        </div>
    )
}
你没有和你的onChange一起传递一个参数,这是一个非常常见的错过 – 但是选择/选项组合有点不太明显.

它应该看起来像:

class Sorting extends React.Component {

    constructor(props) {
      super(props);

      this.opts = [
          ['Price (low)',];

      this.state = {
        selected: 0,// default value
      }

      this.onChange = this.onChange.bind(this);
    }

    onChange(i) {
      const [text,order] = opts[i.target.value];
    };

    render() {
      return (
          <div>
              <select onChange={this.onChange} value={this.state.selected}>
                  {this.opts.map(([text],i) =>
                      <option key={i} value={i}>{text}</option>
                  )}
              </select>
          </div>
      )
    }
}
ReactDOM.render(<Sorting />,document.getElementById("a"));

注意我删除了你的类和样式以保持简单.另请注意,您使用的是大写的Select和Option – 除非这些是自定义内部组件,否则它们应该是小写的.

注意2我还介绍了状态,因为select的状态需要存储在某个地方 – 如果你在这个组件之外维护选择框的状态,你显然可以使用props / callbacks的组合来保持这个值高一级.

http://codepen.io/cjke/pen/egPKPB?editors=0010

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读