获取<选择>从状态设置的defaultValue。反应MUI

发布于 2025-01-17 08:22:25 字数 3679 浏览 0 评论 0原文

我已经研究这个错误几天了,但找不到任何可以修复它的东西。

我试图做的是填充来自本地存储的预选值并与获取请求数据连接。选择请求数据填充为菜单选项,默认选择应保存在本地,因此当用户刷新或离开返回时,他们的联赛仍会被选中。

我在渲染时获取要在 console.log() 中发送的数据,但它不会填充

这是我有问题的代码:

import React, { useState, useEffect } from  "react";

import { 
AppBar, Toolbar, Tabs, Tab, Button, Box, Menu, MenuItem, Divider, Typography, Grid, Select, FormControl, } from '@mui/material';

export default function NavBar(props){
    const [leagues, setLeagues] = useState([]);
    const [currentLeague, setCurrentLeague] = useState()

    useEffect(() => {
        getLeagues();
        setCurrentLeague(JSON.parse(localStorage.getItem('currentLeague')));
     }, []);

    const getLeagues = () => {
        fetch('/draft/get-user-leagues')
            .then((response) => response.json())
            .then((data) => {
                setLeagues(data)
            })
    }

    function handleLeagueChange(e) {
        localStorage.setItem('currentLeague', JSON.stringify(e.target.value));
    }   

    function leagueDropdown(leagues) {
        if (leagues.length === 0) {
            return (<Button
                    component={Link}
                    to='/create-league'
                    >
                        Create New League <AddCircleIcon sx={{marginLeft:'10px'}}/>
                    </Button>
            )
        } else {
        console.log("current League: " + currentLeague.name);
        console.log(currentLeague)
        return (
            <Select
                defaultValue={currentLeague}
                onChange={handleLeagueChange}
            >
                {leagues.map((league, index) => {
                    return <MenuItem 
                                value={league}
                            > 
                                {league.name}
                            </MenuItem>
                })}
            </Select>
        )
    }

    return (
    <AppBar>
        <Toolbar>
            <FormControl>
                {leagueDropdown(leagues)}
            </FormControl>
        </Toolbar>
    </AppBar>
    )
}

如果我手动输入“leagues[1]”,我可以获得要填充的 defaultValue,但我无法使用 currentLeague 填充它。

任何建议将不胜感激!

编辑以添加响应:

    [
  {
    "name": "TestLeague2",
    "owner": "0e31ac27-8978-49cb-81e0-fa6259bdad2b",
    "year": 2022,
    "id": 1
  },
  {
    "name": "TestLeague2",
    "owner": "0e31ac27-8978-49cb-81e0-fa6259bdad2b",
    "year": 2022,
    "id": 2
  },
  {
    "name": "TestLeague2",
    "owner": "0e31ac27-8978-49cb-81e0-fa6259bdad2b",
    "year": 2022,
    "id": 3
  },
  {
    "name": "TestLeague55",
    "owner": "0e31ac27-8978-49cb-81e0-fa6259bdad2b",
    "year": 2022,
    "id": 4
  },
  {
    "name": "TestLeague55",
    "owner": "0e31ac27-8978-49cb-81e0-fa6259bdad2b",
    "year": 2022,
    "id": 5
  },
  {
    "name": "Jacob's League",
    "owner": "0e31ac27-8978-49cb-81e0-fa6259bdad2b",
    "year": 2022,
    "id": 6
  },
  {
    "name": "test234",
    "owner": "0e31ac27-8978-49cb-81e0-fa6259bdad2b",
    "year": 2022,
    "id": 7
  },
  {
    "name": "teasdf",
    "owner": "0e31ac27-8978-49cb-81e0-fa6259bdad2b",
    "year": 2022,
    "id": 8
  },
  {
    "name": "teasdf",
    "owner": "0e31ac27-8978-49cb-81e0-fa6259bdad2b",
    "year": 2022,
    "id": 9
  },
  {
    "name": "teasdf",
    "owner": "0e31ac27-8978-49cb-81e0-fa6259bdad2b",
    "year": 2022,
    "id": 10
  },
  {
    "name": "please1",
    "owner": "0e31ac27-8978-49cb-81e0-fa6259bdad2b",
    "year": 2022,
    "id": 11
  }
]

I've been working on this one bug for a couple of days and cannot find anything that will fix it.

What I'm attempting to do is populate the pre-selected value that comes from the local storage and connects with fetch request data. The select request data populates as the menu options and the default select should be saved locally so when the user refreshed or leaves the comes back, their league is still selected.

I'm getting the data to send in console.log() when it renders, but it will not populate the <Select default={currentLeague}>.

Here's my code in question:

import React, { useState, useEffect } from  "react";

import { 
AppBar, Toolbar, Tabs, Tab, Button, Box, Menu, MenuItem, Divider, Typography, Grid, Select, FormControl, } from '@mui/material';

export default function NavBar(props){
    const [leagues, setLeagues] = useState([]);
    const [currentLeague, setCurrentLeague] = useState()

    useEffect(() => {
        getLeagues();
        setCurrentLeague(JSON.parse(localStorage.getItem('currentLeague')));
     }, []);

    const getLeagues = () => {
        fetch('/draft/get-user-leagues')
            .then((response) => response.json())
            .then((data) => {
                setLeagues(data)
            })
    }

    function handleLeagueChange(e) {
        localStorage.setItem('currentLeague', JSON.stringify(e.target.value));
    }   

    function leagueDropdown(leagues) {
        if (leagues.length === 0) {
            return (<Button
                    component={Link}
                    to='/create-league'
                    >
                        Create New League <AddCircleIcon sx={{marginLeft:'10px'}}/>
                    </Button>
            )
        } else {
        console.log("current League: " + currentLeague.name);
        console.log(currentLeague)
        return (
            <Select
                defaultValue={currentLeague}
                onChange={handleLeagueChange}
            >
                {leagues.map((league, index) => {
                    return <MenuItem 
                                value={league}
                            > 
                                {league.name}
                            </MenuItem>
                })}
            </Select>
        )
    }

    return (
    <AppBar>
        <Toolbar>
            <FormControl>
                {leagueDropdown(leagues)}
            </FormControl>
        </Toolbar>
    </AppBar>
    )
}

I can get the defaultValue to populate if I manually put in 'leagues[1]' but I cannot populate it using currentLeague.

Any advice would be appreciated!

Edit to add the response:

    [
  {
    "name": "TestLeague2",
    "owner": "0e31ac27-8978-49cb-81e0-fa6259bdad2b",
    "year": 2022,
    "id": 1
  },
  {
    "name": "TestLeague2",
    "owner": "0e31ac27-8978-49cb-81e0-fa6259bdad2b",
    "year": 2022,
    "id": 2
  },
  {
    "name": "TestLeague2",
    "owner": "0e31ac27-8978-49cb-81e0-fa6259bdad2b",
    "year": 2022,
    "id": 3
  },
  {
    "name": "TestLeague55",
    "owner": "0e31ac27-8978-49cb-81e0-fa6259bdad2b",
    "year": 2022,
    "id": 4
  },
  {
    "name": "TestLeague55",
    "owner": "0e31ac27-8978-49cb-81e0-fa6259bdad2b",
    "year": 2022,
    "id": 5
  },
  {
    "name": "Jacob's League",
    "owner": "0e31ac27-8978-49cb-81e0-fa6259bdad2b",
    "year": 2022,
    "id": 6
  },
  {
    "name": "test234",
    "owner": "0e31ac27-8978-49cb-81e0-fa6259bdad2b",
    "year": 2022,
    "id": 7
  },
  {
    "name": "teasdf",
    "owner": "0e31ac27-8978-49cb-81e0-fa6259bdad2b",
    "year": 2022,
    "id": 8
  },
  {
    "name": "teasdf",
    "owner": "0e31ac27-8978-49cb-81e0-fa6259bdad2b",
    "year": 2022,
    "id": 9
  },
  {
    "name": "teasdf",
    "owner": "0e31ac27-8978-49cb-81e0-fa6259bdad2b",
    "year": 2022,
    "id": 10
  },
  {
    "name": "please1",
    "owner": "0e31ac27-8978-49cb-81e0-fa6259bdad2b",
    "year": 2022,
    "id": 11
  }
]

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

陪我终i 2025-01-24 08:22:25

使用 currentLeague 状态并实际完全控制选择输入。使用 value 属性而不是您在初始渲染后尝试更改的 defaultValue 属性。

您可以直接从 localStorage 初始化 currentLeague 状态。在 onChange 处理程序中对正常的 React 状态更新进行排队,并使用 useEffect 挂钩将状态更改保存到 localStorage。

您不能使用对象作为选择输入的选项值,因此我建议使用 league.id 属性作为选择值。

示例:

export default function NavBar(props){
  const [leagues, setLeagues] = useState([]);
  const [currentLeague, setCurrentLeague] = useState(
    JSON.parse(localStorage.getItem('currentLeague')) || ''
  );

  useEffect(() => {
    getLeagues();
  }, []);

  useEffect(() => {
    localStorage.setItem('currentLeague', JSON.stringify(currentLeague));
  }, [currentLeague]);

  const getLeagues = () => {
    fetch('/draft/get-user-leagues')
      .then((response) => response.json())
      .then((data) => {
        setLeagues(data)
      });
  };

  function handleLeagueChange(e) {
    setCurrentLeague(e.target.value);
  }   

  function leagueDropdown(leagues) {
    if (leagues.length === 0) {
      return (
        <Button component={Link} to='/create-league'>
          Create New League <AddCircleIcon sx={{marginLeft:'10px'}}/>
        </Button>
      )
    } else {
      return (
        <Select
          value={currentLeague}
          onChange={handleLeagueChange}
        >
          {leagues.map((league, index) => (
            <MenuItem key={league.id} value={league.id}> 
              {league.name}
            </MenuItem>
          ))}
        </Select>
      );
    }
  }

  return (
    <AppBar>
      <Toolbar>
        <FormControl>
          {leagueDropdown(leagues)}
        </FormControl>
      </Toolbar>
    </AppBar>
  );
}

Use the currentLeague state and actually fully control the select input. Use the value prop instead of the defaultValue prop that you are trying to change after the initial render.

You can initialize the currentLeague state directly from localStorage. Enqueue normal React state updates in the onChange handler and use an useEffect hook to persist the state changes to localStorage.

You can't use object for the select input's option values, so I suggest using the league.id property as the select value.

Example:

export default function NavBar(props){
  const [leagues, setLeagues] = useState([]);
  const [currentLeague, setCurrentLeague] = useState(
    JSON.parse(localStorage.getItem('currentLeague')) || ''
  );

  useEffect(() => {
    getLeagues();
  }, []);

  useEffect(() => {
    localStorage.setItem('currentLeague', JSON.stringify(currentLeague));
  }, [currentLeague]);

  const getLeagues = () => {
    fetch('/draft/get-user-leagues')
      .then((response) => response.json())
      .then((data) => {
        setLeagues(data)
      });
  };

  function handleLeagueChange(e) {
    setCurrentLeague(e.target.value);
  }   

  function leagueDropdown(leagues) {
    if (leagues.length === 0) {
      return (
        <Button component={Link} to='/create-league'>
          Create New League <AddCircleIcon sx={{marginLeft:'10px'}}/>
        </Button>
      )
    } else {
      return (
        <Select
          value={currentLeague}
          onChange={handleLeagueChange}
        >
          {leagues.map((league, index) => (
            <MenuItem key={league.id} value={league.id}> 
              {league.name}
            </MenuItem>
          ))}
        </Select>
      );
    }
  }

  return (
    <AppBar>
      <Toolbar>
        <FormControl>
          {leagueDropdown(leagues)}
        </FormControl>
      </Toolbar>
    </AppBar>
  );
}

Edit getting-select-defaultvalue-to-set-from-a-state-react-mui

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文