每当 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,因此是切片语法。