【问题标题】:Component not render the newest value?组件不呈现最新值?
【发布时间】:2022-11-28 07:27:44
【问题描述】:

我已经习惯了 redux。我的问题是 itemList 正确呈现最新值,但来自挂钩状态的 Checkbox 的值未获得最新值。应该检查所有项目列表,但事实并非如此。尽管我 console.log 映射函数中的值,它仍然获得最新值并且查找函数是正确的。

 
export default function Component(props) {
  const dispatch = useDispatch();
  const { itemList } = useSelector((state) => state.AllCourses);

  const [values, setValues] = useState({
    all: true,
    items: []
  });

  useEffect(() => {
    dispatch(
      someActions.getItemList(payload)
    ); //this will get latest itemList
  }, []);

  useEffect(() => {
    if (itemList.length) {
      const newValues = {
        all: true,
        items: itemList.map((item) => ({
          select: true,
          id: item.id,
        })),
      };
      setValues(newValues);
    }
  }, [itemList]);

  return (
      <Box ml={4}>
        { itemList?.map((item) => {
            return (
              <Box key={item.id}>
                <Checkbox
                  name={item.name}
                  value={values?.items?.find((itemVal) => item.id === itemVal.id)?.select}
                />
              </Box>
            );
          })}
      </Box>
  );
}

`

尝试了几种解决方案,但仍然不正确

【问题讨论】:

    标签: reactjs react-redux rxjs


    【解决方案1】:

    看起来您正在使用 Material UI。对于复选框组件,您需要设置 checked 道具。

    import Checkbox from '@mui/material/Checkbox';
    
    const label = { inputProps: { 'aria-label': 'Checkbox demo' } };
    
    export default function Checkboxes() {
      return (
        <div>
          <Checkbox {...label} defaultChecked />
          <Checkbox {...label} />
          <Checkbox {...label} disabled />
          <Checkbox {...label} disabled checked />
        </div>
      );
    }
    

    如果您使用带有类型复选框的 html 输入标签,那么您必须再次相应地设置 checked 属性,请参见下文。

    <label for="vehicle2"> I have a car</label><br>
      <input type="checkbox" name="vehicle3" value="Boat" checked>
    

    【讨论】:

      猜你喜欢
      • 2021-11-10
      • 2020-01-10
      • 1970-01-01
      • 1970-01-01
      • 2020-06-21
      • 1970-01-01
      • 2016-02-23
      • 2020-07-11
      • 1970-01-01
      相关资源
      最近更新 更多