代码之家  ›  专栏  ›  技术社区  ›  alfredopacino

状态更改时重新渲染

  •  0
  • alfredopacino  · 技术社区  · 6 年前

    我正在努力重新渲染组件 BookmarkButton 点击它的图标。 基本上,这里是场景。一 Item 我用 书签按钮 书签按钮 显示星形图标(项目已添加书签)或仅显示轮廓(项目未添加书签)。事实上,这种情况非常普遍。 问题是 书签按钮 状态更改时不重新渲染。。

    class Item extends Component {
        static navigationOptions = ({ navigation,state }) => ({
            headerTitle: "",
            headerTintColor: 'white',
            headerRight: <RightSide navigation={navigation} /> ,
        })
        constructor(props) {
            super(props);
        }
    

    右侧组件

    class RightSide extends Component {
    
        render(){
            const { navigation } = this.props;
            const { params } = navigation.state;
    
            return  (
                <View style={{flex:1,flexDirection:"row"}}>
                    <BookmarkButton id={params.id} />
                </View>
            )
    
        }
    }
    

    书签按钮组件

     class BookmarkButton extends Component {
    
            constructor(props)  {
                super(props);
                this.state = {
                    bookmarked: false
                }
            }
            async componentDidMount(){
            let c = await this.checkBookMark(this.props.id)
            await this.promisedSetState({bookmarked: c})
        }
    
            async _toggleBookmark(id) {
    
                let b = await this.checkBookMark(id) //check if the ID is present in bookmarks @returns boolean
                    b ? await this.removeBookMark(id) : await this.addBookMark(id)
                this.setState({bookmarked:b})
            }
            promisedSetState = (newState) => {
            return new Promise((resolve) => {
                this.setState(newState, () => {
                    resolve()
                });
            });
        };
            render () {
    
                let icon = this.state.bookmarked ? "md-star" : "md-star-outline"
                return(
                    <TouchableOpacity
                        onPress={() => this._toggleBookmark(this.props.id)}
                        <Ionicons name={icon} color="white" size={30} />
                    </TouchableOpacity>
                )}
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   Andrew    6 年前

    我想我知道你的问题是什么。

    您正在检查某个项目之前是否已添加书签。我想如果没有预订的话 this.checkBookMark(id) b === false

    如果返回false,则您将使用将其添加到书签列表中 await this.addBookMark(id)

    然而,这是重要的部分。然后将状态设置为的值 b ,即 false . 您应该将状态的值设置为 !b

    你的州应该成为

    this.setState({bookmarked: !b})