我将首先声明我是 React.js 的完全初学者
我已经创建了一个我正在处理的项目示例,我在其中调用 componentDidMount() 中的 API 并返回一组对象,将其设置为状态。这是它的样子:
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
thing: []
};
}
componentDidMount() {
this.setState({
thing: [
{
status: "running",
test: "testing"
}
]
});
}
render() {
return (
<div>
<h1 className="mt-5 mb-5">{ this.state.thing[0].status }</h1>
<button className="mt-5" onClick={ this.handleUpdate } value="not running">
Click to change
</button>
</div>
);
}
Run Code Online (Sandbox Code Playgroud)
}
我知道 setState 在根据文档使用时不能保证更新。我还发现了“forceUpdate()”,并且文档建议尽可能少地使用它。尽管如此,我尝试使用它,但无济于事。
我能够在 componentDidMount() 运行期间和渲染的 h1 元素中 console.log 新状态,但我无法在渲染中实际显示它,因为它首先渲染一个空状态数组。
我的问题是:有没有办法在我的程序运行渲染之前强制我的状态更新,以便我能够看到它,如果没有,我如何能够看到我的新状态反映在 JSX 中?
旁注:我的 JSX 按钮中有一个 …
我正在向node.js服务器发出POST请求,但我无法让它工作.这是我的要求:
const headers = {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': 'this-can-be-anything',
};
export const postVote = (id, vote) =>
fetch(`${uri}/posts/${id}`, {
method: 'POST',
headers,
body: JSON.stringify({options: vote}),
}).then(response => response.json())
.then(data => data)
.catch(err => console.log(err));
Run Code Online (Sandbox Code Playgroud)
该函数接受'id'和'vote'两个字符串.id被用作请求中URI的一部分,并且投票作为选项提供,因此API知道如何处理它.两个参数都正确传递:
id = '8xf0y6ziyjabvozdd253nd'
vote = 'upVote'
Run Code Online (Sandbox Code Playgroud)
这是一个指向服务器/ API的GitHub存储库的链接:
以及触发请求时网络的屏幕截图:
更新:添加了显示状态200的第二个屏幕截图.虽然它显示了这个并且似乎已经成功,但它仍然没有发布到服务器并且信息保持不变.