首页 > 解决方案 > 在请求模块中设置状态

问题描述

我正在制作一个小型 react.js 应用程序并计划调用两个不同的 API。第一个 API 给了我特定的坐标,然后我将在我的第二个 API 调用中动态使用它。我的计划是通过将坐标保存到请求模块中的状态来保存坐标,但不断收到“this.setState is not a function”。多读一点,我相信我需要让我的请求成为一个胖箭头功能,但还没有成功。关于如何在请求模块中设置状态以及如何动态更新第二个 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>
        );
    }
}```

标签: reactjsapirestrequestnode-modules

解决方案


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

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

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

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

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

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

箭头函数是首选方法。


推荐阅读