【问题标题】:useState doesnt inititalize on fetched data on first renderuseState 不会在第一次渲染时对获取的数据进行初始化
【发布时间】:2020-05-05 10:00:38
【问题描述】:

当这个组件被加载时, fetch 函数应该获取数据并使用 reducer 将数据存储在 store 中。当我使用 useSelector 选择该数据并使用 useState 初始化该值时,它不会在第一次渲染中得到更新。我希望使用 useState 获取和存储数据。请帮助我在 state 变量中使用 useState 存储获取的数据,以便在第一次渲染时初始化获取的数据。

import { useDispatch, useSelector } from 'react-redux';
import { fetchQA } from '../../store/actions/qp';
import ListQA from '../../components/ListQA';

const QAScreen = props =>{
    subjectId = props.route.params.subjectId;

   const dispatch = useDispatch()



       // fetching the data using dispatch

    useEffect(()=>{
        dispatch(fetchQA(subjectId))
    },[dispatch]);

    const selectedQuestions = useSelector(state => state.qa.questionAndAnswers);

    **const [userTestDetails,setUserTestDetails] = useState(selectedQuestions);**



    return(<View>
        <Text> welcome to QA Screen</Text>
        <FlatList   **data={userTestDetails}** // not updating on initial render
                    keyExtractor={item=>item.questionId}
                    renderItem={itemData => <ListQA data={itemData.item} index={itemData.index} />}
        />
    </View>
    )
}

【问题讨论】:

  • 我不明白您为什么将 selectedQuestions 放在当地状态。你是否在selectedQuestions 中获得价值?

标签: reactjs react-native react-redux react-hooks


【解决方案1】:

你不需要将从redux获得的数据存储到状态中,你可以直接使用那个值,除非你想做一些本地操作

const QAScreen = props =>{
    subjectId = props.route.params.subjectId;

   const dispatch = useDispatch()



       // fetching the data using dispatch

    useEffect(()=>{
        dispatch(fetchQA(subjectId))
    },[dispatch]);

    const userTestDetails = useSelector(state => state.qa.questionAndAnswers);





    return(<View>
        <Text> welcome to QA Screen</Text>
        <FlatList   data={userTestDetails}
                    keyExtractor={item=>item.questionId}
                    renderItem={itemData => <ListQA data={itemData.item} index={itemData.index} />}
        />
    </View>
    )
}

此外,由于您正在调度一个在 reducer 中获取和更新数据的操作,因此您不会立即获得数据是正确的,如果您想更新状态,则需要使用 @987654322 @

const QAScreen = props =>{
    subjectId = props.route.params.subjectId;

   const dispatch = useDispatch()



       // fetching the data using dispatch

    useEffect(()=>{
        dispatch(fetchQA(subjectId))
    },[dispatch]);

    const selectedQuestions = useSelector(state => state.qa.questionAndAnswers);
    const [userTestDetails,setUserTestDetails] = useState(selectedQuestions);
    useEffect(() => {
          setUserTestDetails(userTestDetails);
    }, [selectedQuestions]);



    ...
}

【讨论】:

    猜你喜欢
    • 2020-08-25
    • 2022-01-19
    • 1970-01-01
    • 2017-06-21
    • 1970-01-01
    • 2021-08-12
    • 2020-11-20
    • 2021-10-21
    • 1970-01-01
    相关资源
    最近更新 更多