Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在React中为JSON数据调用外部函数_Javascript_Reactjs - Fatal编程技术网

Javascript 在React中为JSON数据调用外部函数

Javascript 在React中为JSON数据调用外部函数,javascript,reactjs,Javascript,Reactjs,我正在学习React并能够在我的各种组件中提取API数据 我会这样打Axios电话: componentDidMount(){ axios.get("https://api.someurl.com/some-request/").then((response)=>{ this.setState(()=>{ return { mydata: response.data } })

我正在学习React并能够在我的各种组件中提取API数据

我会这样打Axios电话:

componentDidMount(){
    axios.get("https://api.someurl.com/some-request/").then((response)=>{
        this.setState(()=>{
           return {
             mydata: response.data
           }
        })
    })
}
这一切都是可行的,因此我的下一步是将API调用移动到外部函数/文件,并传递参数以使API调用可重用。这主要是因为API需要使用授权头、时间戳等进行保护,所以我希望所有这些都在一个地方完成。虽然我似乎找不到正确的方法

我想做的是:

// Inside of components:
componentDidMount(){
  this.setState(()=>{
   return {
     mydata: externalFunction({this.state.someArg})
   } 
  })
}

// Some external module
function externalFunction(args) {
  // create authorization header, make call
  return { "name":"John", "age":25, "city":null }
}
外部模块应该是React类(我不需要state,它只是JSON数据)、React函数还是简单地使用JavaScript函数?无论我尝试什么,Axios调用的返回值似乎都是未定义的。再说一次,我是新手,所以可能遗漏了一些重要的东西


任何例子都将不胜感激。谢谢。

Axios调用是异步的。你不能马上从他们那里归还一些东西。如果您想提供一个函数来包装您的api请求,它必须接受回调作为参数,该参数在请求完成时被调用。只有这样,您才能使用以下数据调用
setState

// Inside of components:
componentDidMount(){
  fetchData({this.state.someArg}, data => this.setState({data});
}

// Some external module
function fetchData(args, callback) {
  axios.get(/* use args here... */).then(response => callback(response.data))
}
或者(可能更好)您的外部函数返回:


Axios调用是异步的。你不能马上从他们那里归还一些东西。如果您想提供一个函数来包装您的api请求,它必须接受回调作为参数,该参数在请求完成时被调用。只有这样,您才能使用以下数据调用
setState

// Inside of components:
componentDidMount(){
  fetchData({this.state.someArg}, data => this.setState({data});
}

// Some external module
function fetchData(args, callback) {
  axios.get(/* use args here... */).then(response => callback(response.data))
}
或者(可能更好)您的外部函数返回: