TypeError.无法读取React JS中未定义的属性 "value"。无法读取React JS中未定义的属性 "value"。

问题描述 投票:0回答:1

我对react JS相当陌生,我已经实现了2个下拉框,其选项通过点击API来显示。我想获得所选的值,但我得到了以下错误。

TypeError: Cannot read property 'value' of undefined.

到目前为止,我只是尝试从一个下拉框中获取值。

这是我的代码。

import React from 'react';
import Select from 'react-select';
import './Search.css';

class SearchForm extends React.Component {
constructor(props){
  super(props);
this.state={
filtered :[],
values1 :[],
values2 :[],
selectedCategory:''
}
this.handleChange = this.handleChange.bind(this);
}

handleChange(event) {
  try{
  this.setState({selectedCategory: event.target.value});
} catch (err) {
  console.error('err', err);}}

componentDidMount() {
  this.fetchData1()
  this.fetchData2()
}

fetchData1 = async () => {
  await fetch('/category/all')
    .then(res => res.json())
    .then(res =>
      this.setState({
        values1: res,
      }),
    )
    .catch(error => console.log(error))
}

fetchData2 = async () => {
  await fetch('/loc/all')
    .then(res => res.json())
    .then(res =>
      this.setState({
        values2: res,
      }),
    )
    .catch(error => console.log(error))
}

async handleSubmit(event){
      event.preventDefault();
try{

const url ='/jobs/all/'
const Response = await fetch((url),{
    method: `GET`,
    mode: 'cors',
        headers: { 
            'Accept': 'application/json'
          }});

const filtered = [];

const res = await Response.json();

const Location = this.menu2.value
const Category = this.menu1.value

console.log(Location)
console.log(Category)

Object.keys( res ).forEach( function( key ) {
    if( res[key].location === Location && res[key].category === Category ) {
        filtered[key] = res[key];}
});
this.setState({filtered})
console.log(this.state.filtered)
        }
 catch (err) {
    console.error('err', err);}
    };
    render() {
      let option1 = []
      if (this.state.values1) {
        this.state.values1.forEach(eachCategory => {
          let Category = {}
          Category.value = eachCategory.id
          Category.label = eachCategory.category
          option1.push(Category)
        })
      }
      console.log(option1)
      let option2 = []
      if (this.state.values2) {
        this.state.values2.forEach(eachLocation => {
          let Location = {}
          Location.value = eachLocation.id
          Location.label = eachLocation.location
          option2.push(Location)
        })
      }
      console.log(option2)
      return (
        <div>
        <form action="/search" onSubmit={this.handleSubmit.bind(this)}>
          <Select options={option1} value={this.state.selectedCategory} placeholder='Category' onChange={this.handleChange}>
          </Select>
          <Select options={option2} placeholder='Location'/>
          <button>Find</button>
        </form>
        {this.state.filtered.map((data)=>{
          //  return <div>{data.location}</div>  // you can render here list items
          return (
          <div className="flex-container">
          <div key={data.id}>
          <div>Job Title: {data.category}</div>
          <div>Location: {data.location}</div>
          <div>Position: {data.position}</div>
          <div>Duration: {data.duration}</div>
          <div>Skills Required: {data.skills_req}</div>
          <div>Apply By: {data.apply_by}</div>
          <div>Starting Date: {data.starting_date}</div>
          <div>Stipend: {data.stipend}</div>
          <div>About Work: {data.about_work}</div>
          <div>Perks: {data.perks}</div>
          </div>
          </div>)

        })}
        </div>
      );
    }
  }

export default SearchForm;

请指出我哪里错了。

javascript reactjs api react-select react-state
1个回答
0
投票

那么,根据 react-select 您正在处理的文件 onChange 以一种错误的方式。应该就是这样的。

 handleChange = selectedOption => {
    this.setState({ selectedOption });
    console.log(`Option selected:`, selectedOption);
  };

https:/www.npmjs.compackagereact-select

所以,在你的情况下,你只需要更改 this.setState({selectedCategory: event.target.value});this.setState({selectedCategory: event}); :

handleChange(event) { //give it a proper name, say selectedValue instead ofevent'
  try{
  this.setState({selectedCategory: event}); //no need of event.target.vaue; in fact that will be undefined
} catch (err) {
  console.error('err', err);}}

请注意: Select 异于常人 select 在这里你可以用 e.target.valuehandleChange 方法。该 Select 带着 react-select 包,因此您需要遵循相应的用法。


-1
投票

你没有将事件发送到 handleChange 方法。

试试吧

onChange={e => this.handleChange(e)}
热门问题
推荐问题
最新问题