如何在React Native中不使用任何API调用的情况下重新渲染组件?

时间:2019-03-28 07:58:30

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

enter image description here

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

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

借助Map组件中的异步变量,我将让Map知道隐藏标记。但是问题是我该如何重新渲染地图组件?

更新的问题

Dan的解决方案对我有用。但是现在我有一个小问题。当我像下面在this.setState中那样使用componentWillMount时,它会向我发出警告。那么,根据接收到的道具的价值,我还能使用什么其他方法来显示/隐藏我的标记呢?

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 }    

1 个答案:

答案 0 :(得分:5)

您的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组件中执行以下操作。您无需修改​​状态,只需使用传入的道具即可。

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>
  )
}
相关问题