简体   繁体   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>
        )
     }
}

I'd like to sync this.text whenever I click button to PUT the value. 我想同步this.text每当我按一下按钮, PUT值。 so the flow is to fetch first then change value, click button PUT value, after PUT , then fetch again 所以流程是先fetch然后更改值,在PUT之后单击按钮PUT值,然后再次获取

You don't have to fetch the data from backend to synchronise the value with the current text. 您无需从后端获取数据即可将值与当前文本同步。 Instead use setState callback in your onMouseDown as: 而是在onMouseDown使用setState回调为:

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

Here the state will be set before it makes a put call and as you're having the updated value, you don't have to fetch the value. 在这里,状态将在进行放置调用之前设置,并且由于您拥有更新的值,因此无需获取值。 When the component is unmounted and mounts again, it will fetch the updated value from your componentDidMount . 卸载组件并再次安装时,它将从componentDidMount获取更新的值。

Read more here 在这里阅读更多

Also

In the render function, use onChange instead of onMouseDown (Which you're not even using) because that would be less confusing. 在渲染函数中,使用onChange而不是onMouseDown (甚至不使用),因为这样可以减少混乱。 Use debounce so that you don't have to make many API calls on every change. 使用反跳,这样您就不必在每次更改时都进行许多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