You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native如何在接口请求响应回调中渲染Lottie等组件?

修正方案

核心逻辑是通过组件状态控制动画的渲染,具体修改如下:

  • 在state中新增控制动画显隐的状态字段
  • 接口返回结果为true时,修改对应状态值触发组件重渲染
  • 在render方法的return中通过状态值条件渲染LottieView组件

修正后的完整代码

import LottieView from 'lottie-react-native'; // 注意提前引入对应依赖

export default class Register extends Component{
  constructor(props){
    super(props);
    this.state = {
      // 原有业务变量
      showSuccessLottie: false // 新增动画控制状态,默认不显示
    };   
  }

  buttonClick = () =>{
    // 原有业务变量定义
    const requestOptions = {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({/* 你的请求参数 */})
    };
    fetch('api_url',requestOptions)
    .then((response) => { return response.json() } ) 
    .catch((error) => console.warn("fetch error:", error))
    .then((response) => {
      console.log(response)
      // 注意如果接口返回的是布尔值true,可直接写if(response),避免类型不匹配导致判断失效
      if(response == "true"){
        // 修改状态触发组件重渲染
        this.setState({showSuccessLottie: true})
      }
    })
  }

  render(){
    return (
      <>
        {/* 原有文本输入框、按钮等业务组件 */}
        {/* 条件渲染Lottie动画 */}
        {this.state.showSuccessLottie && (
          <LottieView
            style={styles.success}
            source={require("./lottie/success.json")}
            autoPlay={true}
            loop={false}
          />
        )}
      </>
    )
  }
}

额外说明

如果需要动画播放完成后自动隐藏,可以监听LottieView的onAnimationFinish回调,在回调方法中将showSuccessLottie改回false即可。

内容的提问来源于stack exchange,提问作者Light Yagami

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 07:54:02