Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
283 views
in Technique[技术] by (71.8m points)

reactjs - Redux with React Native state not updating

I tried to add a recipe to favourites using Redux with React Native. If I use the state in the favicon.js this works fine but does not work with Redux.

This is my favicon.js


    import React, {useState} from 'react'
    import { FontAwesome } from '@expo/vector-icons'
    import { View, TouchableOpacity,StyleSheet, Text, Alert } from 'react-native'
    import { connect } from 'react-redux'
    import { toggleFavId, isFavourite } from '../actions'
    
    const FavIcon = ({recipeid, toggle, isFav, text}) => {
    
      // const [isFavNew, setFavNew] = useState(false)
    
      // const toggleFav = (recipeid) =>{
      //   setFavNew(!isFavNew)
      //   console.log(`Entered toggle ${recipeid} isfavnew = ${isFavNew}`)
      // }
    
       return (
            <View>
                <TouchableOpacity style={styles.favItem} onPress={() => {toggle(recipeid)}}>
                    <FontAwesome name={isFav == true ? 'heart' : 'heart-o'} size={40} color='red' />
                   <Text> {text}</Text>
                </TouchableOpacity>
            </View>
        )
    }
    
    const mapStateToProps = (state) =>({
        favids: state.favids,
    })
    
    const mapDispatchToProps = (dispatch) => ({
        toggle: (recipeid) => dispatch(toggleFavId(recipeid)),
        isFav: (recipeid) => dispatch(isFavourite(recipeid)),
    })
    
    export default connect(mapStateToProps,mapDispatchToProps)(FavIcon)
    
    const styles = StyleSheet.create({
        container: {
          flex: 1,
          flexDirection: 'column',
          backgroundColor: '#fff',
          alignItems: 'flex-start',
          justifyContent: 'center',
        },
        favItem: {
          flexDirection: 'row',
          alignItems: 'center',
          justifyContent: 'flex-start',
          marginTop:10,
          paddingTop:15,
          paddingBottom:15,
          marginLeft:30,
          marginRight:30,
          backgroundColor:'#00BCD4',
          borderRadius:10,
          borderWidth: 1,
          borderColor: '#fff',
          height: 75,
          width: 300,
        }
      });

This if the reducer....the code enters the TOGGLE switch but the state is not updated with the new values.


    import {TOGGLE, IS_FAVOURITE} from '../actions'
    
    export const favids = (state=[], action) => {
        const {type, recipeid} = action
    
        const newRecipe = {
            recipeid: recipeid,
            is_fav: true,
        }
    
        switch (type) {
            case TOGGLE: {
                console.log(`Toggle State = ${JSON.stringify(state)}`)
                console.log(`NEW REcipe ${JSON.stringify(newRecipe)} `)
                // console.log(`Toggle State after adding = ${JSON.stringify(state)}`)
                // return state.map(item=>{ 
                //     state.recipeid === recipeid ? 
                //         {...item, newRecipe} : {...item,newRecipe}
                // })
                return {...state, newRecipe}
            }
            case IS_FAVOURITE: {
                console.log(`Is Favourite state =${JSON.stringify(state)}`)
                return state.map(item=>{ 
                    item.recipeid === recipeid ? 
                        {...item, is_fav: !item.is_fav} : item
                })
            }
            default:
                return state
        }
    }

I've tried different methods of updating the state (see below) but the state is not updated. I've commented out the older code which was not working

            // return state.map(item=>{ 
            //     state.recipeid === recipeid ? 
            //         {...item, newRecipe} : {...item,newRecipe}
            // })
            return {...state, newRecipe}

Any help would be appreciated.

This is the index.js file from the '../actions' folder


    export const TOGGLE = 'TOGGLE'
    export const toggleFavId = id => ({
        type: 'TOGGLE',
        recipeid: id
    })
    
    export const IS_FAVOURITE = 'IS_FAVOURITE'
    export const isFavourite = id => (
        {
            type: 'IS_FAVOURITE',
            recipeid: id
        }
    )
    
    export const TOGGLE_FAV = 'TOGGLE_FAV'
    export const toggleFav = id => ({
        type: 'TOGGLE_FAV',
        recipeid: id,
    })

this is the VisibleFavicon.js file


    import {connect} from 'react-redux'
    import Favicon from '../components/favicon'
    
    const mapStateToProps = state =>({
        favids: state
    })
    
    const mapDispatchToProps = dispatch => ({
        toggleFavIds: id => dispatch ({
            type: 'TOGGLE',
            id 
        }),
    isFavourite : id => dispatch ({
        type: 'IS_FAVOURITE',
        id
    }),
    })
    
    export default connect(mapStateToProps, mapDispatchToProps)(Favicon)

question from:https://stackoverflow.com/questions/65877975/redux-with-react-native-state-not-updating

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try to get whole state of redux instead of state.favids and wherever you want to use that state you can access it like props.state.favids :

 const mapStateToProps = (state) =>({
 favids: state,
 })

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...