如何在输入值中设置我的值

时间:2019-10-21 14:32:57

标签: javascript reactjs forms api

我试图在输入值中设置我的值,但是一直在控制台中获取undefined时,我想从API中将值设置为value,但是我却不知道如何在输入值中设置值并且我还尝试删除ref并查看,但是当我在输入中设置undefined时,值输入仍然显示value={2}

这里是:

this.state = {
      // movie: [],
      user: this.props.value,
      text: "",
      errors: []
    };


async componentDidMount() {
    try {
      const res = await fetch(
        `https://softbike.dev.myddp.eu/api/1/deliveries/user1/`
      );
      const movie = await res.json();
      console.log(movie);
      this.setState({
        movie: movie.pk
      });
    } catch (e) {
      console.log(e);
    }
  }

  handleChange(event) {
    this.setState({
      [event.target.name]: event.target.value
    });
    console.log(this.state);
  }

这里是输入代码:

<div className="row">
          <div className="col-sm-12">
            <label id="p"> UZYTKOWNIK</label>
            <input
              type="text"
              ref="user"
              className="form-control"
              name="user"
              value={movie.id}
              onChange={this.handleChange}
            />
           <p>g {this.state.value}</p>
          </div>

请帮助我解决此问题。

2 个答案:

答案 0 :(得分:0)

<div className="col-sm-12">
   <label id="p"> UZYTKOWNIK</label>
   <input
      type="text"
      ref="user"
      className="form-control"
      name="user"
      value={this.state.movie && this.state.movie.id}
      onChange={this.handleChange}
 />
</div>

答案 1 :(得分:0)

尝试一下:

this.state = {
    movie: {},
    user: this.props.value,
    text: "",
    errors: []
};


componentDidMount() {
    const fetchMovie = async () => {
        try {
          const res = await fetch(`https://softbike.dev.myddp.eu/api/1/deliveries/user1/`);
          const movie = res.json();
          console.log(movie);
          this.setState({
             ...this.state,
             movie: movie.pk
          });
        } catch (e) {
           console.log(e);
        }
    }
    fetchMovie(); // Call async fundtion
}

  handleChange(event) {
    this.setState({
      [event.target.name]: event.target.value
    }, () => {
        console.log(this.state);
        // Because setState is async function, so you have to console.log in callback of
        // setState to see the new data of this.state
    });
  }

输入:

<div className="row">
    <div className="col-sm-12">
        <label id="p"> UZYTKOWNIK</label>
        <input
          type="text"
          ref="user"
          className="form-control"
          name="user"
          defaultValue={this.state.movie.id}
          onChange={this.handleChange}
        />
    <p>g {this.state.value}</p>
</div>