这是我的主页组件:
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/