我正在尝试使用访存来检索我的数据,然后使用setState将其应用到componentDidMount中。我收到的日志显示安装了组件,在Fetch之后的所有操作,包括简单的控制台日志均无法正常工作。我的语法有什么简单的错误吗?我已经验证了api确实可以正常工作。
import React, { Component } from 'react';
import { Editor } from '@tinymce/tinymce-react';
let policyContent = '';
class TinyEditor extends Component {
constructor(props) {
super(props);
this.state = { content: '' };
this.handleEditorChange = this.handleEditorChange.bind(this);
this.handleClick = this.handleClick.bind(this);
}
componentDidMount() {
console.log(`Component did mount`);
fetch("/policy")
.then(res => res.json())
.then((result) => {
console.log(result);
console.log(`You got your results... now what?`);
policyContent = result;
console.log(policyContent[0]);
this.setState({policyContent});
});
}
handleEditorChange(content, editor) {
this.setState({ content });
}
handleClick(e) {
e.preventDefault();
console.log(`Button was clicked.`);
console.log(this.state.content);
}
render() {
return (
<div>
<div className="container">
<Editor
apiKey='yf9eajz93s3akrlb24b8ja9xcszddbxx22x4ug8c2q5boxw3'
className="mceEditor"
id='myTextArea'
init={{
height: 500,
editor_selector: 'mceEditor',
menubar: false,
browser_spellcheck: true,
contextmenu: true,
branding: false,
plugins: [
'advlist autolink lists link image charmap print preview anchor',
'searchreplace visualblocks code fullscreen',
'insertdatetime media table paste code help wordcount'
],
toolbar:
'undo redo | formatselect | bold italic backcolor | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | help'
}}
onEditorChange={this.handleEditorChange}
value={this.state.content}
/>
<button onClick={this.handleClick}>Save</button>
</div>
</div>
)
}
}
导出默认TinyEditor;
我已经使用在线api运行您的代码。一切正常。请替换代码componentDidMount
并检查输出以进行测试。
componentDidMount() {
console.log(`Component did mount`);
fetch(`https://opentdb.com/api.php?amount=10&difficulty=hard&type=boolean`)
.then(res => res.json())
.then((result) => {
console.log(result);
console.log(`You got your results... now what?`);
policyContent = result.results[0];
console.log(policyContent);
this.setState({content: policyContent.category});
});
}