reactjs - 属性 'setUser' 在类型 'Readonly<{}> & Readonly<{ children?: ReactNode; }>' 上不存在
当我使用 yarn start 运行我的 Reactjs + ElectronJS 应用时,它运行良好。但当我尝试用 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);
}
}
答案#1
错误涉及你组件上 props 的推断类型。它正在退回到 React 对 props 的默认值。
两个案例被交叉以定义此默认情况...
Readonly<{}> & Readonly<{ children?: ReactNode; }>a) 没有 prop 键
b) 可能存在一个 children 属性键(如果你通过 JSX 向元素添加了一些内容,例如标签、文本或渲染属性)。
为了解决这个问题,你需要明确指出你的组件所使用的 props 类型。
根据 JSX TypeScript 文档,我相信这最终可能看起来像这样,以确保对 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>
)
}
}
