我正在使用Codemirror创建一个组件,但似乎我的代码有问题,因为当我尝试更新主组件的状态时,应用程序会中断浏览器。我的研究指出至少存在一个无限循环,至少在调试时我可以看到。
希望你们中的某个人能帮助我解决这个问题,也许是我的错,谢谢。
我的主要组件:
import React, { Component, PropTypes } from 'react';
import Editor from '../editor';
import Preview from '../preview';
class Playground extends Component {
constructor(props) {
super(props);
this.state = {
code: 'Hi I am a component',
newCode: ''
};
this.handleCodeChange = this.handleCodeChange.bind(this);
}
handleCodeChange(code) {
// Everything works fine until this step, when the component wants to update the state, start the infinite loop
this.setState({ newCode: code });
}
loadCode(code) {
this.refs.editor.setCode(code);
}
render() {
return (
<div>
<Editor
ref='editor'
codeText={this.state.code}
onChange={this.handleCodeChange}
/>
<Preview code={this.state.newCode} />
</div>
);
}
}
Playground.propTypes = {
component: PropTypes.string
};
export default Playground;
我的编辑器组件:
import React, { Component, PropTypes } from 'react';
import style from './style';
import CodeMirror from 'codemirror';
import 'codemirror/mode/javascript/javascript';
class Editor extends Component {
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
}
componentDidMount() {
this.editor = CodeMirror.fromTextArea(this.refs.editor, {
lineNumbers: this.props.lineNumbers,
matchBrackets: true,
mode: 'javascript',
readOnly: this.props.readOnly,
smartIndent: false,
tabSize: this.props.tabSize,
theme: this.props.theme
});
this.editor.on('change', this.handleChange);
}
componentDidUpdate() {
if ( !this.props.readOnly ) {
this.editor.setValue(this.props.codeText);
}
}
handleChange() {
if ( !this.props.readOnly && this.props.onChange ) {
this.props.onChange(this.editor.getValue());
}
}
render() {
let _className = style.editor;
return (
<div className={ _className }>
<textarea ref="editor" defaultValue={this.props.codeText} />
</div>
);
}
}
Editor.propTypes = {
className: React.PropTypes.string,
codeText: PropTypes.string,
lineNumbers: PropTypes.bool,
onChange: PropTypes.func,
readOnly: PropTypes.bool,
tabSize: PropTypes.number,
theme: PropTypes.string
};
Editor.defaultProps = {
className: '',
lineNumbers: false,
readOnly: false,
tabSize: 2,
theme: 'one-dark'
};
export default Editor;
我的预览组件
import React, { Component, PropTypes } from 'react';
class Preview extends Component {
constructor(props) {
super(props);
}
render() {
return (
<div>{this.props.code}</div>
);
}
}
Preview.propTypes = {
code: PropTypes.string
};
export default Preview;
请让我知道是否需要更多信息或其他内容。
提前感谢您的配合。
解决方案
我从编辑器组件中删除了这个片段。
componentDidUpdate() {
if ( !this.props.readOnly ) {
this.editor.setValue(this.props.codeText);
}
}
原因是因为这种方法会给编辑器设置一个新值,表示更新,然后该过程无限重复开始。如果您手动加载编辑器内容,这种方法可以使用,但这不是我的情况。
谢谢 Anthony。
this.handleCodeChange = this.handleCodeChange.bind(this);
的目的是什么?尝试将其删除。 - Gopinath Shiva