gpt4 book ai didi

javascript - 如何将函数结果返回给 React 组件?

转载 作者:行者123 更新时间:2023-12-04 08:12:17 25 4
gpt4 key购买 nike

看起来很简单,但我想不通,你将如何从导入到组件的函数中返回结果?
当我从 .then() 控制台记录它们时,我得到了正确的结果,但似乎无法将它们返回到组件。
例子:
函数.js

export const getFeatures = (e) => {
let features = Client.getEntries({
content_type: '###',
'fields.type': `${e}`
})
.then(response => {
return response.items;
})
.catch(console.error)
}

组件.js
import {getFeatures} from './functions.js'

const App = () => {
let x = getFeatures('home');
console.log(x)

return ( ... )


// expecting the array response [{},{},{}, .. etc], but getting undefined instead


}

最佳答案

getFeatures不返回任何东西,你应该改变它来返回它的 promise :

export const getFeatures = (e) => {
return Client.getEntries({
content_type: '###',
'fields.type': `${e}`
})
.then(response => {
return response.items;
})
.catch(console.error)
}
然后在 App 添加一个功能状态,当您调用 getFeatures 时会更新它在 useEffect 调用的安装阶段:
import { useState, useEffect } from 'react'
import {getFeatures} from './functions.js'

const App = () => {
// create a features state
const [features, setFeatures] = useState([])

// on mount call 'getFeatures'
useEffect(() => {
getFeatures('home')
.then(setFeatures) // chain returned promise and pass setFeatures to update features

}, []) // add empty array to tell to run the code on mount only

// do some mapping with features, this is for example purpose
// remember to add an unique key to each feature
return ( features.map(feature => {
return <div key={feature.id}>{feature.name}: {feature.realease}</div>
}))
}

关于javascript - 如何将函数结果返回给 React 组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65894512/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com