【问题标题】:Setting the state within a request module在请求模块中设置状态
【发布时间】:2021-04-27 23:53:10
【问题描述】:

我正在制作一个小型 react.js 应用程序并计划调用两个不同的 API。第一个 API 给了我特定的坐标,然后我将在我的第二个 API 调用中动态使用它。我的计划是通过将坐标保存到请求模块中的状态来保存坐标,但不断得到“this.setState 不是函数”。多读一点,我相信我需要使我的请求成为一个胖箭头函数,但还没有成功地做到这一点。关于如何在请求模块中设置状态以及如何动态更新第二个 API 调用的任何想法?感谢所有帮助!

class App extends Component {
    constructor(props) {
        super(props);
        this.state = {
            lat: '',
            long: '',
        };
    }

    componentDidMount() {
        let request = require('request');

        let options1 = {
            method: 'GET',
            json: true,
            url: url1,
            headers: {
                'content-type': 'application/json',
            },
        };
        request(options1, function (error1, response1, body1) {
            if (error1) throw new Error(error1);
            this.setState({ lat: response1, long: response1 });
        });

        let options = {
            method: 'GET',
            json: true,
            url: url,
            qs: { lat:`${this.state.lat}` , lng: `${this.state.long}`, dt: '2018-01-24T10:50:52.283Z' },
            headers: {
                'content-type': 'application/json',
                'x-access-token': `${process.env.REACT_APP_UV_API_KEY}`,
            },
        };
        request(options, function (error, response, body) {
            if (error) throw new Error(error);
            console.log(response.body.result.uv);
        });
    }
    render() {
        return (
            <div>
                <header>
                    <Home />
                </header>
            </div>
        );
    }
}```

【问题讨论】:

    标签: reactjs api rest request node-modules


    【解决方案1】:

    我想指出 this.setState 是以重新渲染为代价的,从我在渲染方法中看到的内容来看,您并不真正依赖 lat, long 进行渲染。因此,最好将其用作常量变量而不是状态变量。

    如果您想坚持将它们用作状态变量,有很多方法可以做到这一点。箭头函数如下所示:

    request(options1, (error1, response1, body1) => {
          if (error1) throw new Error(error1);
          this.setState({ lat: response1, long: response1 });
        });
    

    this 需要有正确的工作范围,箭头函数可以解决这个问题。你可以阅读更多here

    您甚至可以将this 分配给另一个变量并在请求中使用它

        const self = this;
        request(options1, function(error1, response1, body1) {
          if (error1) throw new Error(error1);
          self.setState({ lat: response1, long: response1 });
        });
    

    箭头函数是首选方法。

    【讨论】:

      猜你喜欢
      • 2021-06-02
      • 1970-01-01
      • 1970-01-01
      • 2018-05-05
      • 1970-01-01
      • 2021-09-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多