reactjs - React native - 将函数导入使用“this”的组件
问题描述
我有一个名为 getGooglePlaces....的函数,它当前位于一个代表组件的类中。它非常复杂,所以我想将它移到另一个文件(帮助文件)并导入它。但是我收到错误消息“无法读取未定义的属性‘刷新’”。
我假设它指的是“this”....那么我该如何制作它以便我的组件从正在导入的函数中识别“this”?(好像“this”属于正在导入它的组件)
getGooglePlaces = () => {
//add loading spinner unless we are refreshing
if (this.state.refreshing === false) this.setState({ loading: true });
//hit google places api
const uri = `etcetc`;
fetch(uri)
.then(resp => resp.json())
.then((dataBack) => {
this.setState({
data: uniqueDataArray,
loading: false,
refreshing: false,
解决方案
一旦你将函数移出组件,它的this
上下文就不再是 React 组件。我建议将您要引用的状态传递给函数
function getGooglePlaces(componentState) => {
...
return {
data: uniqueDataArray,
loading: false,
refreshing: false
}
}
然后使用函数返回的结果设置组件的状态
class MyReactComponent extends Component {
...
const result = getGooglePlaces(this.state)
this.setState(result)
...
}
希望有帮助!
推荐阅读
- azure - How can I override the host settings of my azure function locally?
- php - 未找到 Mobile_WS_Controller
- javascript - 如何将新数据输入推送到列表顶部
- django - 如何在 Django 中正确设置 AJAX
- javascript - 使用快速路由显示 React 页面
- javascript - 我从 for 循环中获得的数组总和返回 NaN (Javascript)
- javascript - ReactJS — 创建 Refs 并访问 DOM 元素以使用 fullpage.js
- nestjs - 如果存在 uid 选项,则返回特定用户,否则返回整个用户列表
- glsl - OpenGL:将 RGBA 转换为浮点数
- swift - 从 Firestore 快照更新 ChatModel 字典中的现有项目