gpt4 book ai didi

javascript - 为什么 ReactJs 更新全局变量?

转载 作者:行者123 更新时间:2023-12-03 21:07:21 26 4
gpt4 key购买 nike

我是 ReactJs 的新手,我真的不知道如何向你解释这个问题,但我正在开发一个 React 应用程序,我试图制作一个表单生成器组件,并且我成功地创建了它。但是当我尝试在任何其他组件中使用它时,每件事都开始以一种奇怪的方式运行:(例如,它正在更新一个全局变量,我不知道这是怎么发生的。我的代码:

字段.js

/**
*
* React component that render a control fields using a JSON schema.
*
* @file crezmo-fields.js
* @summary React forms component
* @author CREZMO <crezmo.com>
*
*/
class CrezmoFields extends React.Component {

/**
* constructor.
*
* @since 1.0.0
* @return {void}
*/
constructor (props){
super(props);
this.state = {
fields : this.props.fields
};
this.handleChange = this.handleChange.bind(this);
}

/**
* Render.
*
* @since 1.0.0
* @return {ReactElement}
*/
render (){
return (
<div>
{this.state.fields.map((field , index)=>{

switch (field.type) {
case 'text' : {
console.log(this);
return this.TextField(field , index);
break;
}
}

})}
</div>
)
}


/**
* Handle Changes.
*
* @since 1.0.0
* @return {void}
*/
handleChange (index , new_value){
// Create an updated field object
const updated_field = this.state.fields[index];
updated_field.value = new_value;

// Create an updated fields object
const updated_fields = this.state.fields;
updated_fields[index] = updated_field;

// Update the component
this.setState({fields : updated_fields});

// Pass data to parent
(typeof(this.props.hasChanged) === "function" && this.props.hasChanged(this.state.fields))

}


/**
* Text field.
*
* @since 1.0.0
* @param {object} data - the field data.
* @param {number} field index number in state.fields
* @returns {ReactElement} a react element of the field
*/
TextField = (data , index) => {
const self = this;
return (
<div key={index} className={`cf-field cf-${data.type} cf-id-${data.id}`}>
<label htmlFor={data.id}>
{data.title}
</label>
<div className="cf-control-wraper">
<input
type='text'
placeholder = {data.placeholder}
name={data.id}
value={data.value}
onChange={
(e) => {
self.handleChange(index , e.target.value);
}
}
/>
</div>
<span className="cf-field-desc">{data.description}</span>
</div>
)
};

}

应用程序.js

var fields = [ //why is this array getting updated when i type in the input field ? 
{
type : 'text',
id : "my_id",
}
];

class TestForms extends React.Component {

/**
* constructor.
*
* @since 1.0.0
* @return {void}
*/
constructor (props){
super(props);
this.state = {
formfields: this.props.fields
};
}


render (){
return (
<div>
<CrezmoFields fields={this.state.formfields}
hasChanged={(state)=>{
this.setState({formfields: state})
}}
/>
</div>
)
}

}

ReactDOM.render(
<TestForms fields={fields}/>,
document.getElementById('app')
);

我错过了什么?提前致谢:)

最佳答案

因为你永远不会复制数组。

Javascript 对象通过引用传递,因此传递对象仍会改变原始对象。

关于javascript - 为什么 ReactJs 更新全局变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48694916/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com