React - 如何将返回的数据从导出函数传递给组件?

新手上路,请多包涵

如何将从 get 请求接收到的数据传递给组件?无论我尝试什么都行不通,但我的想法如下面的代码所示。谢谢!

     export function data() {
        axios.get('www.example.de')
            .then(function(res) {
                return res.data
            })
            .then(function(data) {
                this.setState({
                    list: data
                })
            })
    }

    import {data} from './api.js';

    class Test extends React.Component {
        constructor(props) {
            super(props);
            this.state = {
                list: ""
            };
        }

        componentWillMount() {
            data();
        }
        render() {
            return <p > this.state.list < /p>
        }
    }

原文由 javascripting 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 294
2 个回答

You call this.setState inside of data()->then callback, so this is context of the then callback function.相反,您应该使用箭头函数(它没有自己的上下文)并将组件的 this 传递给 data 函数使用 call

 export function data() {
    axios.get('www.example.de')
        .then(res => res.data)
        .then(data => {
            this.setState({
                list: data
            })
        })
}

import {data} from './api.js';

class Test extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            list: ""
        };
    }

    componentWillMount() {
        data.call(this);
    }
    render() {
        return <p > this.state.list < /p>
    }
}

但是,您的数据服务必须不知道 setState 并且,事件更多,期望从反应组件传递 this 。您的数据服务必须负责从服务器检索数据,但不负责更改组件状态,请参阅 单一职责原则。此外,可以从另一个数据服务调用您的数据服务。因此,您的数据服务应该返回承诺,组件可以使用它来调用 setState

    export function data() {
       return axios.get('www.example.de')
           .then(res => res.data)
   }

接着

componentWillMount() {
    data().then(data=>{
        this.setState({
            list: data
        })
    });
}

原文由 Maxim Kuzmin 发布,翻译遵循 CC BY-SA 4.0 许可协议

你的 api 应该对你的组件一无所知,你可以使用 callback 轻松做到这一点,就像这样 -

 export function data(callback) {
    axios.get('www.example.de')
        .then(res => callback({ data: res.data }))
        .catch(err => callback({ error: err }));
}

通过这样做,您可以轻松地对您的 api 进行单元测试

所以在你的 Test 组件中,你只需做 -

 componentWillMount() {
  data(result => {
    const { data, error } = result;
    if (error) {
      // Handle error
      return;
    }

    if (data) {
      this.setState({ list: data });
    }
  });
}

原文由 grgmo 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题