Javascript React:推送到useState中的数组

时间:2019-09-13 07:03:39

标签: reactjs typescript

我试图在状态对象menuHistory下存储字符串数组,并在页面更改props.location更新时以'first'初始化它,从而触发useEffect ()然后尝试将位置推入数组。

我得到的错误是..

Argument of type '{ menuHistory: number; }' is not assignable to parameter of type 'SetStateAction<{ menuHistory: string[]; }>'.
  Type '{ menuHistory: number; }' is not assignable to type '{ menuHistory: string[]; }'.
    Types of property 'menuHistory' are incompatible.
      Type 'number' is not assignable to type 'string[]'.ts(2345)
import React, {useEffect, useState} from 'react';
import {Link} from 'react-router-dom';

interface propsInterface {
    location: any; 
  }

const SideMenu: React.FC<propsInterface> = (props) => {
  const { global } = useContext(Context) as {global: any; setGlobal: React.Dispatch<React.SetStateAction<any>>};
  const [state, setState] = useState({menuHistory: ['first']});

  useEffect(() => {
    const location = props.location.pathname.split('/')[2];
    setState({menuHistory: state.menuHistory.push(location)});
  }, [props.location])

  return (
    <div className='nav'>
        <Link to={{pathname: '/my/identity'}}><div id='identity'>Identity</div></Link>
        <Link to={{pathname: '/my/accounts'}}><div id='accounts'>Accounts</div></Link>
        <Link to={{pathname: '/my/claims'}}><div id='claims'>Claims</div></Link>
        <hr/>
        <Link to={{pathname: '/my/profile'}}><div id='profile'>Profile</div></Link>
        <Link to={{pathname: '/my/password'}}><div id='password'>Password</div></Link>
        <Link to={{pathname: '/my/settings'}}><div id='settings'>Settings</div></Link>
        <Link to={{pathname: '/my/logout'}}><div id='logout'>Log out</div></Link>
  </div>
  );
}

export {SideMenu};

3 个答案:

答案 0 :(得分:1)

push返回元素的索引,使用数组扩展添加该项:

setState(state => ({menuHistory: [...state.menuHistory, location]}));

答案 1 :(得分:1)

就像@Clarity一样,push返回推送项目的索引,该运算符也使对象发生突变。最佳做法是创建另一个数组(例如,如建议的那样散布先前的值),然后在其中添加新的条目,如下所示:

setState({menuHistory: [...state.menuHistory, location]});

答案 2 :(得分:0)

您已经定义了{menuHistory:['first']},它是array。 尝试使用concat而不是push。

   setState({menuHistory: state.menuHistory.concat(location)});