简体   繁体   English

ReactJS 如何在 class 的构造函数中添加变量 state

[英]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.在尝试将 var 放入其中时,我不断收到我的变量未定义的错误。 state, here is my code state,这是我的代码

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.仅当搜索输入字段更改时才声明 z 。 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.在 React 中执行此操作的正确方法是在构造函数中将 state.setSearch 设置为“”。 Then in the search input onChange, call (event)=>this.setState({setSerch: event.target.value})然后在搜索输入onChange,调用(event)=>this.setState({setSerch: event.target.value})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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