Javascript 未捕获类型错误:can';“定义财产”;x";:对象不可扩展
我正在尝试恢复一个写在Javascript 未捕获类型错误:can';“定义财产”;x";:对象不可扩展,javascript,reactjs,Javascript,Reactjs,我正在尝试恢复一个写在reactjs16.4上的旧项目,该项目包含webpack3。 现在我已经升级了所有的库,ReactJS到v17和webpack到v5 所以,我得到了这个错误: Uncaught TypeError: can't define property "lang": Object is not extensible 代码是: class LandingPage extends React.Component { render() { const
reactjs16.4
上的旧项目,该项目包含webpack3
。
现在我已经升级了所有的库,ReactJS
到v17
和webpack
到v5
所以,我得到了这个错误:
Uncaught TypeError: can't define property "lang": Object is not extensible
代码是:
class LandingPage extends React.Component {
render() {
const { i18n } = this.props;
if ((typeof this.props.match.params.lng !== 'undefined') && ((this.props.match.params.lng == 'en') || (this.props.match.params.lng == 'lt'))) {
this.props.lang = this.props.match.params.lng.toString();
}
else {
this.props.lang = 'lt';
}
if (this.props.lang !== i18n.language) {
i18n.changeLanguage(this.props.lang, (err) => {
if (err) return console.log('something went wrong loading', err)
});
}
return (
<div>
<Preloader />
<Header />
<SectionMain />
<Footer />
</div>
)
}
}
类登录页扩展React.Component{
render(){
const{i18n}=this.props;
如果((this.props.match.params.lng!=='undefined')&((this.props.match.params.lng=='en')| |(this.props.match.params.lng=='lt')){
this.props.lang=this.props.match.params.lng.toString();
}
否则{
this.props.lang='lt';
}
if(this.props.lang!==i18n.language){
i18n.changeLanguage(this.props.lang,(err)=>{
if(err)返回console.log('加载出错',err)
});
}
返回(
)
}
}
从那以后似乎有些事情发生了变化。
如何修复它?该代码从来都不正确,因为它写入了
道具
:
if ((typeof this.props.match.params.lng !== 'undefined') && ((this.props.match.params.lng == 'en') || (this.props.match.params.lng == 'lt'))) {
this.props.lang = this.props.match.params.lng.toString();
}
else {
this.props.lang = 'lt';
}
您的组件只能从props对象读取props,而不能写入。改变是通过使对象不可扩展来增加强制
如何修复它取决于何时需要该信息以及如何处理该信息(显示的代码中似乎没有使用this.props.lang
):
渲染
,则将其设置为本地变量
render
中更改状态,在创建或装载时执行一次)
this
(组件实例)上的属性中
props
可以在组件实例的生命周期内更改。道具由父级而不是组件进行有效的状态管理。因此,如果您从道具中获取信息,则需要在道具更改时重新获取
这可能让我们想到#4:
lang
。当它这样做时,它将获得新的lang
作为更新的道具,并将重新渲染这是一个语言变量。取决于URL代码或语言开关。但这里是一个逻辑检查:变量是否设置,如果不设置-设置默认语言->
lt
@Kuzma-恐怕我不理解注释。lang存储当前选定语言的语言代码。它可以有两种状态:英语->'en'和立陶宛语->'lt'。但对于一个没有选择两种语言中任何一种的情况,这段代码是编写的。它检查变量是否未定义-设置默认语言。所以其他组件可以访问该语言的代码。这是不正确的,但在过去它达到了它的目的:)@Kuzma-听起来你可能想要。