简体   繁体   中英

ReactJS how to add variable in a constructor state in class

I keep getting the error that my variable is not defined while trying to put var in this. state, here is my code

code

in this code the variable is supposed to get the input user has typed and update the set Search

class App extends React.Component {
constructor() {
  super();
  this.state = {
    city: null,
    setCity: null,
    search: null,
    setSearch: z
  };
  }
  componentDidMount() {
   const fetchApi = async () => {
    const url = `https://api.openweathermap.org/data/2.5/weather? 
    q=${this.state.setSearch}&appid=f10cf2869c0 
    372186a094a41fc576f46`;
    const response = await fetch(url);
    const resJson = await response.json();
    this.setState({ setCity: resJson });
    };
    fetchApi();
   }
   render() {
   return (
          <div>
          <div className="box">
          <div className="inputData">
            <input
             type="search"
             className="inputField"
             onChange={(event) => {
             var z= event.target.value;
            }}   
           />

You are declaring z only when the search input field change. Thus it doesn't exist yet when the contructor is called.

The correct way to do it in React would be to set the state.setSearch to "" in the constructor. Then in the search input onChange, call (event)=>this.setState({setSerch: event.target.value})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM