我正在尝试实现延迟加载。因此,在单击一个api之后,我将promise对象发送到名为Test.js的类。在Test.js中的react.lazy中,我正在解决它。现在,在解决了诺言之后,我想将响应传递给延迟加载组件。但是它仅接受class作为返回类型。有没有一种方法可以将响应数据传递给惰性组件。
Test.js代码
import React, { Suspense } from "react"
import {
View,
Text
} from 'react-native'
import LoadingIndicator from '../../generic_components/presentational/loading_indicator'
import { colors } from '../../../constants'
class Test extends React.Component {
render () {
const { data } = this.props // data is a promise object
const LazyComponent = React.lazy(() => {
return new Promise(resolve => resolve(data)).then(
(response) => { // I want to pass the content of response to Test2.js
return import('./Test2')
}
);
})
return (
<View>
<Suspense fallback={<LoadingIndicator color={colors.purple} />}>
<LazyComponent
/>
</Suspense>
</View>
)
}
}
export default Test
编辑:解决方案 因此,正如AndréPint所说,getter可以完成所需的任务。
因此,在Test.js中
import React, { Suspense } from "react"
import {
View,
Text
} from 'react-native'
import LoadingIndicator from '../../generic_components/presentational/loading_indicator'
import { colors } from '../../../constants'
class Test extends React.Component {
constructor(props){
super(props)
this.response = {}
this.getResponse = this.getResponse.bind(this)
}
getResponse () {
return this.response
}
render () {
const { data } = this.props // data is a promise object
const LazyComponent = React.lazy(() => {
return new Promise(resolve => resolve(data)).then(
(response) => { // I want to pass the content of response to Test2.js
this.response = response
return import('./Test2')
}
);
})
return (
<View>
<Suspense fallback={<LoadingIndicator color={colors.purple} />}>
<LazyComponent
getResponse={this.getResponse}
/>
</Suspense>
</View>
)
}
}
export default Test
在Test2.js中
import React from 'react'
import {
View,
Text
} from 'react-native'
class Test2 extends React.Component {
render () {
const data = this.props.getResponse()
return (
<View>
<Text>{data}</Text>
</View>
)
}
}
export default Test2