gpt4 book ai didi

reactjs - 保存 react 组件并稍后加载

转载 作者:行者123 更新时间:2023-12-02 03:45:02 26 4
gpt4 key购买 nike

我在 React Native 应用程序中有 React 组件,这将返回如下所示的 Smth:

constructor(){
...
this.Comp1 = <Component1 ..... >
this.Comp2 = <Component2 ..... >
}
render(){
let Show = null
if(X) Show = this.Comp1
else Show = this.Comp1
return(
{X}
)
}

并且我的两个组件内部都有一个 API 请求,

所以我的问题是,当条件发生变化并且组件之间切换时,每次组件向该 API 发送请求以获得相同的结果时,

我想知道如何保存构造的组件,他们不会每次都发送请求

最佳答案

实现此目的的方法之一是处理每个子组件内部的隐藏和显示 comp1comp2

所以你仍然会渲染 comp1comp2来自父组件,但您将向每个组件传递一个 prop 来告诉它们是否需要显示或隐藏内部内容,如果显示则渲染正确的组件内容,否则仅渲染空 <Text></Text>

这意味着两个子组件都存在于父组件中,并且它们永远不会被删除,但您可以通过父组件来控制哪个子组件应该显示自己的内容。

因此您的数据仅获取一次。


检查 React js 中的工作示例:https://codesandbox.io/s/84p302ryp9
如果您检查控制台日志,您会发现 comp1 和 comp2 只完成一次提取。


另请检查下面的 React Native 中的相同示例:

class Parent extends Component {
constructor(props)
{
super(props);
this.state={
show1 : true //by default comp1 will show
}
}

toggleChild= ()=>{
this.setState({
show1 : !this.state.show1
});
}

render(){
return (
<View >
<Button onPress={this.toggleChild} title="Toggle Child" />
<Comp1 show={this.state.show1} />
<Comp2 show={!this.state.show1} />
</View>
)
}
}

比较 1:

class Comp1 extends Component
{
constructor(props) {
super(props);
this.state={
myData : ""

}
}

componentWillMount(){
console.log("fetching data comp1 once");
this.setState({
myData : "comp 1"
})
}


render(){
return (
this.props.show ? <Text>Actual implementation of Comp1</Text> : <Text></Text>
)
}
}

比较 2:

class Comp2 extends Component {
constructor(props) {
super(props);
this.state = {
myData2: ""

}
}

componentWillMount() {
console.log("fetching data in comp2 once");
this.setState({
myData2: "comp 2"
});
}


render() {
return (
this.props.show ? <Text>Actual implementation of Comp2</Text> : <Text></Text>
)
}
}

关于reactjs - 保存 react 组件并稍后加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47033290/

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