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

How to re render the component without using any API call in React Native?

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

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

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

更新问题

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

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 }    

你的 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 组件中执行以下操作。您不需要修改状态,只需使用传入的 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>
  )
}