【问题标题】:How to re render the component without using any API call in React Native?如何在不使用 React Native 中的任何 API 调用的情况下重新渲染组件?
【发布时间】:2019-03-28 07:58:30
【问题描述】:

从上图中,我有 2 个视图,当按下棕色或绿色按钮时可以更改它们。因此,当默认情况下已经选择了棕色按钮时,地图中有一个标记。当我按下绿色按钮时,我希望删除地图的标记。

所以我尝试的是在按下绿色按钮时设置一个异步变量,并在 Map 组件中获取该异步变量。

使用地图组件中的异步变量,我会让地图知道隐藏标记。但问题是如何重新渲染我的地图组件?

更新问题

Dan 的解决方案对我有用。但现在我有一个小问题。当我在componentWillMount 中使用this.setState 时,它会给我一个警告。那么我可以使用什么其他替代方法来根据我收到的道具的价值来显示/隐藏我的标记?

if(this.props.isMarkerVisible) {
        this.setState({ showDots: true })
    }
    else {
        this.setState({ showDots: false })
    }

         { this.state.showDots === true &&
                <Marker
                    ref={(mark) => { this.marker = mark; }}
                    coordinate={{ latitude, longitude }}
                    pinColor={colors.primaryColor}
                    image={require('../../../../assets/circle.png')}
                />
            }  

            { this.state.showDots === false &&  null }    

【问题讨论】:

    标签: android reactjs react-native react-native-maps


    【解决方案1】:

    您的Map 组件将在其道具和状态更改时重新渲染

    给你的父组件添加一个状态变量

    this.state = {
      isMarkerVisible: false // Set this to your default value
    }
    

    现在,添加一个设置状态变量的函数

    onPress = isMarkerVisible => {
      this.setState({ 
        isMarkerVisible
      });
    }
    

    最后,修改按钮上的 onPress 事件

    // Green
    <TouchableOpacity
      onPress={() => this.onPress(false)}
    />
    
    // Brown
    <TouchableOpacity
      onPress={() => this.onPress(true)}
    />
    

    修改您的Map 组件,使其接受isMarkerVisible 属性,其值为this.state.isMarkerVisible

    <Map
      ...props
      isMarkerVisible={this.state.isMarkerVisible}
    />
    

    现在在你的Map 组件内部,你需要修改渲染逻辑,下面是一些伪代码。您尚未添加任何 Map 代码,因此我无法提供具体信息。

    If this.props.isMarkerVisible
    Then render the marker
    Else do not render the marker
    

    更新以反映问题

    您可以在 Map 组件中执行以下操作。不需要修改 state,使用传入的 prop 即可。

    renderMarker = (coordinates) => {
      const { isMarkerVisible } = this.props;
      if(!isMarkerVisible) return null;
      return (
        <Marker
          ref={(mark) => { this.marker = mark; }}
          coordinate={{ latitude, longitude }}
          pinColor={colors.primaryColor}
          image={require('../../../../assets/circle.png')}
        />
      )
    }
    
    
    render() {
      const coordinates = { latitude: 0, longitude: 0 }
      return (
        <View>
          { this.renderMarker(coordinates) }
        </View>
      )
    }
    

    【讨论】:

    • 更新了@ShubhamBisht
    • 不幸的是,由于某种原因,我无法在渲染之外使用 renderMarker 函数。这似乎是一些坐标问题。没有其他方法可以在componentWillMount 中使用 setState 吗?也许使用this._isMounted
    • 你能在问题中分享你的渲染方法吗?
    • 答案已更新,以便 renderMarker 函数接受坐标
    猜你喜欢
    • 1970-01-01
    • 2020-08-18
    • 2015-08-18
    • 2021-01-02
    • 2020-02-04
    • 1970-01-01
    • 2016-07-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多