首页 > 解决方案 > 属性 'setUser' 不存在于类型'Readonly<{}> & Readonly<{ children?: ReactNode; }>'

问题描述

当我使用以下命令运行 Reactjs + ElectronJS 应用程序时,它运行良好:yarn start。当我尝试使用以下命令构建它时出现此错误:yarn build。我不明白什么是错的。

Property 'setUser' does not exist on type 'Readonly<{}> & Readonly<{ children?: ReactNode; }>'.

这是产生错误的代码:

export const test = () => ({
 type: 'TEST',
});

export const setUser = (mail, pwd, token, firstname, lastname) => ({
type: 'SET_USER',
payload: {
    Email: mail,
    Pwd: pwd,
    Token: token,
    Firstname: firstname,
    Lastname: lastname,
}
});

我在其他地方使用它来进行身份验证:

  GetInfoFromBack() {
const param : any[] = [];

for (var i = 0; i < arguments.length; ++i) {
  param[i] = arguments[i];
}

if (param[1] === null && param[2] != null) {
  axios.get('http://104.xx.xx.192:xxxx' + param[0], param[2])
  .then(response => {
    if (param[0] === "/get_auth_user") {
      this.props.setUser(response.data.email, this.props.base.Pwd, this.props.base.Token, response.data.firstname, response.data.lastname);
    }
  }).catch(err => {
    alert(err.response.data);
  })
} else {
  alert("ERROR: bad request : " + param);
}
}

标签: reactjstypescriptelectron

解决方案


该错误涉及为组件上的 props 推断的类型。它正在回退到 React 的 props 默认值。

两个案例相交以定义此默认值...

Readonly<{}> & Readonly<{ children?: ReactNode; }>

a) 没有道具键

b) 可能有一个 children 属性键(如果您通过 JSX 向元素添加了一些内容,例如标签、文本或渲染属性)。

要解决此问题,您需要明确说明组件使用的道具的类型。

JSX 打字稿文档中,我相信这最终可能看起来像这样,以确保对 this.props 的访问可以依赖于 setUser 函数......

import {
  setUser
} from './myfile'

interface MyProps {
  children: JSX.Element | JSX.Element[]
  setUser: typeof setUser
}

class Component extends React.Component<MyProps, {}> {
  render() {
    return (
      <h2>
        {this.props.children}
      </h2>
    )
  }
}


推荐阅读