javascript - 如何从一个组件访问单独文件中的其他函数(非组件)的状态值? react js

标签 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文件中页面的状态值?

最佳答案

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

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

请注意,我用 componentDidMount 替换了 componentWillMount,后者更适合执行异步操作。

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);
    });
};

关于javascript - 如何从一个组件访问单独文件中的其他函数(非组件)的状态值? react js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49791936/

相关文章:

javascript - 如何调整客户端和服务器的时间戳差异?

javascript - 从检查输入 radio 的行获取数据

reactjs - "object Object"在 ReactJS 上显示为 Formik 表单的输入值

c - 如何使用fgetc读取文件

Javascript 对象和全局作用域?

javascript - typescript :不可分配给类型错误

reactjs - 使用 TypeScript 编写 React 高阶组件

javascript - 以编程方式绑定(bind)事件 (SyntheticEvent)

C# 语法 : where TResponse, new()

function - 数组被错误地称为子或函数