8

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

4

1 回答 1

0

我没有承诺任何事情,但试试这个,看看它是否有效:

useEffect(()=>{
  (async () => {
    if (id) dispatch(fetchArticle(id));
    await setForm({
      ...form,
      title: title,
      summary: summary,
      severity: severity,
      references: references,
      type: type,
      vulnerabilities: vulnerabilities
    })
  })();
}, []);

然后删除第二个useEffect。如果这不起作用,我们可以看到您的渲染 jsx 代码吗?

于 2021-11-12T17:00:14.183 回答