如何从一个组件访问状态值到另一个文件中的其他功能(不是组件)?反应js

时间:2018-04-12 08:45:09

标签: javascript reactjs function react-native components

这是我的主页组件:

import React from 'react';
import { getData } from '../../../util/network';

export default class Home extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      page: 1,
    };
  }

  async componentWillMount() {
    const val = await getData();
  }

  render() {
    return() {
      // jsx stuffs
    }
  }
}

这是一个名为network.js://的文件,它是一个函数

export const getData = () => {
  const { page } = this.state; // this is undefined now
  const url = `http://randomuser.in/${page}`;
  fetch(url)
    .then(res => res.json())
    .then(res => {
      return res;
    })
    .catch(error => {
      console.log('error:', error);
    });
};

如何在我的network.js文件中访问页面的状态值?

2 个答案:

答案 0 :(得分:2)

您应该将page状态作为参数传递给您的函数:

async componentDidMount() {
  const val = await getData(this.state.page);
}

请注意,我将componentWillMount替换为componentDidMount,这是执行异步操作的首选。

export const getData = (page) => {
  const url = `http://randomuser.in/${page}`;
  fetch(url)
    .then(res => res.json())
    .then(res => {
      return res;
    })
    .catch(error => {
      console.log('error:', error);
    });
};

答案 1 :(得分:0)

您不应该依赖于this.state功能。这不是一个好习惯。您应该只传递该函数中需要的参数/参数。

示例

const val = await getData(this.state.page);
export const getData = (page) => {
  // use page argument that passed
  //...
};
相关问题