gpt4 book ai didi

javascript - 单击按钮时 React setState 不会自动填充数据

转载 作者:行者123 更新时间:2023-11-28 17:00:37 25 4
gpt4 key购买 nike

我正在学习 Web 开发的 Reach。目标:让按钮在每次单击按钮时更新消息“状态”。我没有收到任何可以帮助我解决问题的错误或问题。

{
"name": "reactapp",
"version": "1.0.0",
"description": "React app",
"main": "index.js",
"scripts": {
"start": "webpack-dev-server --hot"
},
"author": "BigD",
"license": "ISC",
"dependencies": {
"babel-core": "^6.26.3",
"babel-loader": "^7.1.5",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"react": "^16.9.0",
"react-dom": "^16.9.0",
"webpack": "^4.39.2",
"webpack-dev-server": "^3.8.0"
},
"devDependencies": {
"webpack-cli": "^3.3.7"
}
}


I have tried redoing the code step by step.
I tried updating the error: Property 'data' does not exist on type 'Readonly<{}>'.

import React from "react";

class App extends React.Component {

constructor() {
super();

this.state = {
data: []
}

this.stateHandler = this.stateHandler.bind(this);
}

stateHandler() {
var item = 'The State';
var dataArray = this.state.data;
dataArray.push(item);
this.setState({data: dataArray });
}

render() {
return (
<div>
<div>{this.state.data} </div>
<button onClick={this.stateHandler}> Click here to update </button>
</div>
);
}
}

export default App;

应该像类(class)中一样显示此消​​息:点击按钮:'国家国家国家'

enter image description here enter image description here

最佳答案

您正在尝试直接显示数组。使用 Array.prototype.join(' '),它将数组转换为空格分隔的字符串并正确渲染。{this.state.data.join(' ')} 将为您解决该问题。

class App extends React.Component {

constructor() {
super();

this.state = {
data: []
}

this.stateHandler = this.stateHandler.bind(this);
}

stateHandler() {
var item = 'The State';
var dataArray = this.state.data;
dataArray.push(item);
this.setState({data: dataArray });
}

render() {
return (
<div>
<div>{this.state.data.join(' ')} </div>
<button onClick={this.stateHandler}> Click here to update </button>
</div>
);
}
}

ReactDOM.render(<App />, document.querySelector('#root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id="root"></div>

关于javascript - 单击按钮时 React setState 不会自动填充数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57615038/

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