一旦 useSelector 钩子返回一个值,有没有办法重新渲染 React-Select 组件?

amb*_*web 2 reactjs react-select redux

我有一个表单,当我在其中输入数据并提交时,我将数据发送到reducer,然后将其保存到SQL 数据库。数据库返回我输入的数据和 ID,并将其存储在我的商店中。

现在我有另一个 React-Select 组件,我希望它将输入的数据显示为DefaultValue.

我正在寻找一种方法,让 React 选择组件在从挂钩返回真值时重新加载useSelector,最好是在该值发生变化时重新加载。

import React, { useEffect } from 'react';
import Select from 'react-select';
import { useDispatch, useSelector } from 'react-redux';
import {
  getSelectOptions,
  getOptions,
  setSelectionValue,
  getBookOptions,
} from '../store/selectReducer';

export default function selectForm() {
  const dispatch = useDispatch();

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

  const autoren = useSelector(getOptions).autorOpts;

  //>>>>>>>>>>>>>> Here I retrieve the desired data from the store <<<<<<<<<<<<<<<<<<<<<<
  const DEFAULTVALUE = useSelector(store => store.authorBook.author);

  const onChangeAut = option => {
    dispatch(setSelectionValue(option));
    dispatch(getBookOptions(option.id));
  };

  return (
    <div>
      <Select onChange={onChangeAut} defaultValue={DEFAULTVALUE} isClearable options={autoren} />
    </div>
  );
}
Run Code Online (Sandbox Code Playgroud)

Kis*_*eel 9

不要使用,defaultValue因为它无法更新。只需使用value组件即可在状态更改时自行更新。

  • 疯狂的!我一整天都在拼命地寻找解决方案,最终它是如此简单!太感谢了! (2认同)