Cannot read property 'map' of undefined while converting a list to a dynamic drop down

前端 未结 1 452
情深已故
情深已故 2021-01-27 16:43

I am working in converting a list of items into a dynamic dropdown option list but I have a problem.

I checked if the props are coming right and they are.

this i

相关标签:
1条回答
  • 2021-01-27 17:09

    Well there are a couple of scenarios that can result in that error.

    1) If your this.props.allKeycodes object doesn't have a allKeycodes property inside of it - const {allKeycodes} = this.props.allKeycodes; this will result in undefined, which then result in calling map on that undefined.

    2) You can get that error, if you don't have a default value when you are passing props in your component/ or you don't check for undefined value. You can check it inside the function, or when calling the function, but it must not be undefined.

    buildSelectOptions = opts => opts && opts.map(....) this code will check if opts isn't falsy and run the next bit of code. Otherwise it will just result in undefined.

    UPDATE

    buildSelectOptions = (opts) => {
      return opts && opts.map((opt) =>  <Option value={opt.id}>{opt.uid}</Option>)
    };
    

    OR

    buildSelectOptions = (opts) => {
        if(opts) {
          return opts.map((opt) =>  <Option value={opt.id}>{opt.uid}</Option>)
        }
    };
    
    0 讨论(0)
提交回复
热议问题