繁体   English   中英

reactjs获取PUT值并将值传递给状态

[英]reactjs fetch PUT value and pass value to state

如何在<code> PUT </ code>之后重新获取

class Mycomponent extends Component {
    state = {
        text: null
    }

    componentDidMount() {
        fetch("http://localhost:3000/books/4")
          .then(response => response.json())
          .then(data => this.setState({ text: data.title  // this data.value is "Learn Javascript" }));
    }

    fetchPUT(val) {
    fetch("http://localhost:3000/books/4", {
        method: "PUT",
        headers: {
            "Content-Type": "application/json; charset=utf-8"
        },
        body: JSON.stringify({ value: val })
        }).then(e => console.log(e));
    }

     onMouseDown = e => {
        this.setState({
          text: this.refs.myinput.value,
        });
        this.fetchPUT(this.refs.myinput.value);
    };
    render() {
        const { text } = this.state;
        return (
            <div>
                <input
                  type="text"
                  value={text}
                  onMouseLeave={this.onMouseLeave}
                  ref="myinput"
                />
            </div>
        )
     }
}

我想同步this.text每当我按一下按钮, PUT值。 所以流程是先fetch然后更改值,在PUT之后单击按钮PUT值,然后再次获取

您无需从后端获取数据即可将值与当前文本同步。 而是在onMouseDown使用setState回调为:

onMouseDown = e => {
        this.setState({
          text: this.refs.myinput.value,
        }, () => {
           this.fetchPUT(this.refs.myinput.value);
        });
    };

在这里,状态将在进行放置调用之前设置,并且由于您拥有更新的值,因此无需获取值。 卸载组件并再次安装时,它将从componentDidMount获取更新的值。

在这里阅读更多

在渲染函数中,使用onChange而不是onMouseDown (甚至不使用),因为这样可以减少混乱。 使用反跳,这样您就不必在每次更改时都进行许多API调用。

onChange = _.debounce((event) => {
   const text = event.target.value;
   this.setState({text}, () => {
       this.fetchPUT(text);
   })
}, 500)

render() {
        const { text } = this.state;
        return (
            <div>
                <input
                  type="text"
                  value={text}
                  onChange={this.onChange}
                />
            </div>
        )
     }

暂无
暂无

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

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