【问题标题】:Property 'setUser' does not exist on type 'Readonly<{}> & Readonly<{ children?: ReactNode; }>'属性 'setUser' 不存在于类型'Readonly<{}> & Readonly<{ children?: ReactNode; }>'
【发布时间】:2020-11-29 22:18:45
【问题描述】:

当我使用以下命令运行我的 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);
}
}

【问题讨论】:

  • 请为使用if 条件的组件添加整个sn-p。如果组件很大,至少包括所有调用/使用setUser 的部分。谢谢...
  • 好的,我刚刚编辑了帖子。我希望这会有所帮助。

标签: reactjs typescript electron


【解决方案1】:

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

两个 case 相交来定义这个默认值...

Readonly&lt;{}&gt; &amp; Readonly&lt;{ children?: ReactNode; }&gt;

a) 没有道具键

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

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

来自JSX typescript documentation,我相信这最终可能看起来像这样,以确保对 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>
    )
  }
}

【讨论】:

  • 伟大的@Xodarap。如果您单击 +50,这将是我的第一个赏金奖 :) 在潜伏了很长时间后才开始在 StackOverflow 上回答。
猜你喜欢
  • 2019-12-11
  • 2020-11-07
  • 2020-01-24
  • 2018-10-11
  • 2018-10-14
  • 2019-02-14
  • 2020-09-20
  • 1970-01-01
  • 2022-01-23
相关资源
最近更新 更多