Redux-Toolkit 和 React Hooks - 存储更改不会触发重新渲染
Posted
技术标签:
【中文标题】Redux-Toolkit 和 React Hooks - 存储更改不会触发重新渲染【英文标题】:Redux-Toolkit and React Hooks - Store change does not trigger re-render 【发布时间】:2020-07-13 12:18:52 【问题描述】:每当 URL 包含带有 ID 的查询参数时,我都会尝试使用来自数据库的信息预填充表单。从数据库中获取信息时,我无法使网站触发重新渲染。组件中的相关代码如下所示。
let id = useParams();
const title, summary, severity, references, type, vulnerabilities = useSelector(
(state: RootState) => state.articles.article
)
useEffect(() =>
if(id) dispatch(fetchArticle(id))
, [])
const [form, setForm] = useState<FormState>(
title: title,
type: type,
summary: summary,
severity: severity,
references: references,
vulnerabilities: vulnerabilities,
autocompleteOptions: autocompleteSuggestions,
reference: "",
vulnerability: "",
)
useEffect(() =>
setForm(
...form,
title: title,
summary: summary,
severity: severity,
references: references,
type: type,
vulnerabilities: vulnerabilities
)
, [title, summary, severity, references, type, vulnerabilities])
我们可以看到 Redux 操作被触发,并且文章状态在商店中更新。我还尝试在钩子内 console.log
以验证它是否运行,但仅在初始渲染时运行。如果我在切片中更改initialState
,那么它会反映在表单中。
let initialState: ArticleState =
loading: false,
error: null,
article:
title: "",
severity: 0,
type: 0,
summary: "",
references: [],
vulnerabilities: [],
id: 0
,
articles: [] as Article[],
autocompleteSuggestions: [] as DropdownItem[]
const ArticleSlice = createSlice(
name: "articles",
initialState,
reducers:
getArticleStart: startLoading,
getArticleFailure: loadingFailed,
getArticleSuccess(state: ArticleState, payload : PayloadAction<Article>)
state.article = payload
state.error = null
state.loading = false
)
export const
getArticleFailure,
getArticleStart,
getArticleSuccess
= ArticleSlice.actions
export default ArticleSlice.reducer
奇怪的是,如果我在页面上保存代码,热重载确实会更新它并触发重新渲染,正确填充表单。
请注意,我使用的是Redux-Toolkit,因此是切片语法。
【问题讨论】:
您最终解决了这个问题吗?我面临着完全相同的问题。 【参考方案1】:我没有任何承诺,但试试这个,看看它是否有效:
useEffect(()=>
(async () =>
if (id) dispatch(fetchArticle(id));
await setForm(
...form,
title: title,
summary: summary,
severity: severity,
references: references,
type: type,
vulnerabilities: vulnerabilities
)
)();
, []);
然后删除第二个useEffect。如果这不起作用,我们可以查看您的渲染 jsx 代码吗?
【讨论】:
以上是关于Redux-Toolkit 和 React Hooks - 存储更改不会触发重新渲染的主要内容,如果未能解决你的问题,请参考以下文章
如何将 redux-toolkit createSlice 与 React 类组件一起使用
从 react-redux 迁移到 redux-toolkit 后使用 configureStore 传递初始状态的最佳方法
Redux流程分析 传统流程和redux-toolkit的使用