下方代码有两处打印,打印的值不一样,需要老师解惑。

来源:10-8 新增类别和删除类别(2)

香饽饽0

2020-05-15

我在使用 hooks 时遇到了问题,不知道怎样才能得到正确结果。
重点在仅有的两处 console.log

import React, { useState, useEffect } from 'react';
import { View, Text, StyleSheet, ScrollView } from 'react-native';
import { useDispatch, useSelector } from 'react-redux';
import { RootState } from '@/models/index';
import { viewportWidth } from '@/utils/index';
import { ICategory } from '@/models/category';
import _ from 'lodash';
import Item from './Item';
import { RootStackNavigation } from '@/navigator/index';
import HeaderRightBtn from './HeaderRightBtn';
import Touchable from '@/components/Touchable';

interface IProps {
    navigation: RootStackNavigation;
}

const fixedItems = [0, 1]

const Category: React.FC<IProps> = (props) => {
    const dispatch = useDispatch();
    const categoryState = useSelector((state: RootState) => state.category);
    const [myCategorys, setMyCategorys] = useState(categoryState.myCategorys);
    const [count, setCount] = useState(0);
    const classifyGroup = _.groupBy(
        categoryState.categorys,
        (item) => item.classify,
    );

    const renderItem = (item: ICategory, index: number) => {
        const disabled = fixedItems.indexOf(index) > - 1
        return (
            <Touchable
                key={item.id}
                onPress={() => {
                    const disabled = fixedItems.indexOf(index) > - 1
                    if (disabled) {
                        return
                    }
                    if (categoryState.isEdit) {
                        setMyCategorys(() =>
                            myCategorys.filter(
                                (selectedItem) => selectedItem.id !== item.id,
                            ),
                        );
                    }
                }}>
                <Item data={item} isEdit={categoryState.isEdit} selected disabled={disabled} />
            </Touchable>
        );
    };

    const renderUnselectedItem = (item: ICategory, index: number) => {
        return (
            <Touchable
                key={item.id}
                onPress={() => {
                    if (categoryState.isEdit) {
                        setMyCategorys(() => [...myCategorys, item]);
                        setCount(count => count + 1)
                    }
                }}
                onLongPress={() => {
                    dispatch({
                        type: 'category/setState',
                        payload: {
                            isEdit: true,
                        },
                    });
                }}>
                <Item
                    data={item}
                    isEdit={categoryState.isEdit}
                    selected={false}
                />
            </Touchable>
        );
    };

    const onSubmit = () => {
	    // 这里打印 useState 的初始值
        console.log('===', myCategorys, '===', count);
        dispatch({
            type: 'category/toggle',
            payload: {
                myCategorys,
            },
        });
    };

    useEffect(() => {
        props.navigation.setOptions({
            headerRight: () => <HeaderRightBtn onPress={onSubmit} />,
        });
        return () => {
            dispatch({
                type: 'category/setState',
                payload: {
                    isEdit: false,
                },
            });
        };
    }, []);

    useEffect(() => {
		// 这里打印正确
        console.info(myCategorys, count);
    }, [myCategorys]);

    return (
        <ScrollView style={styles.container}>
            <Text style={styles.classifyName}>我的分类</Text>
            <View style={styles.classifyView}>
                {myCategorys.map(renderItem)}
            </View>
            <View>
                {Object.keys(classifyGroup).map((classify) => {
                    return (
                        <View key={classify}>
                            <Text style={styles.classifyName}>{classify}</Text>
                            <View style={styles.classifyView}>
                                {classifyGroup[classify].map((item, index) => {
                                    if (
                                        myCategorys.find(
                                            (selectedItem) =>
                                                selectedItem.id === item.id,
                                        )
                                    ) {
                                        return null;
                                    }
                                    return renderUnselectedItem(item, index);
                                })}
                            </View>
                        </View>
                    );
                })}
            </View>
        </ScrollView>
    );
};

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#f3f6f6',
    },
    classifyName: {
        fontSize: 16,
        marginTop: 14,
        marginBottom: 8,
        marginLeft: 10,
    },
    classifyView: {
        flexDirection: 'row',
        flexWrap: 'wrap',
        padding: 5,
    },
});

export default Category;

写回答

1回答

香饽饽0

提问者

2020-05-15

用 useEffect 解决了,需要传入第二参数 [myCategorys]

0
2
香饽饽0
回复
今朝
是的,需要借助useEffect去更新myCategorys
2020-05-15
共2条回复

跨平台应用ReactNative+TypeScript仿喜马拉雅开发App

从入门到实战,掌握用TypeScript开发ReactNative应用

832 学习 · 339 问题

查看课程