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
288 views
in Technique[技术] by (71.8m points)

javascript - React-Native: State changes affecting view only on next action/rerender?

I have a component where user can add items to their shopping cart, next to each item it shows either a plus icon (add) or the number of items of that type in the shopping cart (chosenProducts state variable), adding items works well but for some reason the item count only updates after the next item is added instead of inmediately "reacting" to an added item...

Summary: item count UI doesn't update after item is added, updates after the next item is added (whatever item that is.

const [ chosenProducts, setChosenProducts ] = useState([]);
const [ chosenProductIds, setChosenProductIds ] = useState([]);
const [ data, setData ] = useState([ {id:1}, {id:2}, {id:3}, {id:4}, {id:5}, {id:6} ]);

const showProductCount = (item) =>
    {
        let finds = _.filter(chosenProductIds, id => id == item.id);
        if(finds.length > 0)
        {
            return (<Text style={{ fontSize:16,color:'white' }}>{finds.length}</Text>);
        }
        else
        {
            return (<MaterialCommunityIcon name="plus" style={{ color:'white', fontSize:22 }}/>)
        }
    };

const addItem = (product) =>
    {
        var copy = [...chosenProducts];
        copy.push(product);
        var chosenProductId = _.map(chosenProducts, product => product.id);
        setChosenProducts(copy);
        setChosenProductIds(chosenProductId);
    }


<FlatList showsVerticallScrollIndicator={false} style={{ flex:1}} vertical={true} data={data} keyExtractor={item => item.id.toString()}
       renderItem={({ item, index }) => 
       (<TouchableOpacity onPress={ ()=>{ addItem(item) } } style={{ width:'15%',flexDirection:'column',alignItems:'center'}}>
       <View style={{  width:35,height:35,borderRadius:5,backgroundColor:'rgb(3,91,150)',flexDirection:'column',alignItems:'center',justifyContent:'center' }}>
           {showProductCount(item)}
       </View>
   </TouchableOpacity>)
       
        }
    />

Is it beacuse I'm using a function to return JSX instead of conditional rendering inside JSX itself?


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

1 Reply

0 votes
by (71.8m points)
等待大神答复

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

...