首页 > 解决方案 > 如何在 React 组件中导入的非组件类中使用 props 值

问题描述

我想访问哪个导入哪个this.props.apiendpoint是组件基类。api.jstest.js

# api.js
import axios from 'axios';
export function fetchData(){
   return axios.post(apiendpoint);
}
# App.js
import test from test.js
export default class App extends Component {
  constructor() {
    this.apiendpoint = 'api.example.com';
  }
   
  render() {
    <test apiendpoint = {apiendpoint} />
  }
}

# test.js
import PropTypes from 'prop-types';
import {fetchData}  from api.js;

const test = ({
}) => {
   console.log(this.props.apiendpoint); // this value how to acccess in api.js 
   fetchData();
}
test.propTypes = {
apiendpoint: PropTypes.String,
}
test..defaultProps = {
apiendpoint : null,
}

就像fetchData()我对每个函数都有许多与 API 相关的传递函数,apiendpoint这不是一个好习惯。

任何帮助将不胜感激。

标签: javascriptreactjstypescriptreact-hooksreact-props

解决方案


我会将 apiEndPoint 添加为 fetchData 函数的参数。

# api.js
import axios from 'axios';
export function fetchData(apiendpoint){
   return axios.post(apiendpoint);
}

然后通过传递 prop 作为参数从 test.js 调用它。

import PropTypes from 'prop-types';
import {fetchData}  from api.js;

const test = ({
}) => {
   console.log(fetchData(this.props.apiendpoint));

}

推荐阅读