簡體   English   中英

為什么在redux rerender時狀態總是變回init值

[英]Why state always changes back to init value when redux rerender

當redux重新渲染時,狀態會變回init值,並且useEffect每次都會運行。 好像在redux狀態更改后重新安裝了組件。

控制台打印兩次問好,當我輸入一些文本並單擊“搜索”按鈕時,輸入框變為空。

import React, {useEffect, useState} from "react";
import Button from "react-bootstrap/es/Button";
import fetch from "cross-fetch";
import actions from "@/actions";
import api from "@/api";
import {useDispatch} from "react-redux";


const getData = (title, page) => dispatch => {
    dispatch(actions.notice.loading());
    return fetch(api.notice.list({title, page}), {method: 'POST'})
        .then(response => response.json())
        .then(resultBean => {
            dispatch(actions.notice.success(resultBean.data.list))
        }).catch(error => {
            dispatch(actions.notice.failure(error));
        });
};

const View = _ => {
    const [title, setTitle] = useState('');
    const dispatch = useDispatch();
    useEffect(() => {
        console.log('hello');
        dispatch(getData(title, 1))
    }, []);
    return (
        <>
            <input onChange={e => setTitle(e.target.value)} value={title} type="text"/>
            <Button onClick={e => dispatch(getData(title, 1))}>Search</Button>
        </>
    )

};


export default View;

您未顯示完整的邏輯,以防萬一您dispatch動作並觸發View父級渲染,則View可能會根據其父級的狀況重新渲染甚至卸載。

為了不重新渲染View ,您需要記住它:

// default is shallow comparison
export default React.memo(View); 

對於不卸載的View ,請檢查其父邏輯。

另外,請注意,在const View = _ =>上使用_仍允許您像_.value一樣訪問它,我相信這不是您想要的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM