gpt4 book ai didi

javascript - 刷新时保持状态

转载 作者:行者123 更新时间:2023-12-04 08:58:27 25 4
gpt4 key购买 nike

我开发了一个 React Dapp,我可以在其中添加用户输入的表数据。但是每次刷新页面时数据都消失了,我想知道是否可以将数据保留在表中。如果是,我该怎么做?
这是在表中添加输入数据的代码:

class App extends React.Component {
constructor() {
super();

this.state = {
username: '',
password: '',
items: []
}
};

handleFormSubmit = (e) => {
e.preventDefault();

let items = [...this.state.items];

items.push({
username: this.state.username,
password: this.state.password
});

this.setState({
items,
username: '',
password: ''
});
};

handleInputChange = (e) => {
let input = e.target;
let name = e.target.name;
let value = input.value;

this.setState({
[name]: value
})
};

render() {
return ( <
div className = "App" >
<
Form handleFormSubmit = {
this.handleFormSubmit
}
handleInputChange = {
this.handleInputChange
}
newUsername = {
this.state.username
}
newPassword = {
this.state.password
}
/> <
Table items = {
this.state.items
}
/> <
/div>
);
}
}

class Table extends React.Component {
render() {
const items = this.props.items;
return ( <
div id = "Table" >
<
table >
<
tbody >
<
tr >
<
th > Username < /th> <
th > Password < /th> <
/tr> {
items.map(item => {
return ( <
tr >
<
td > {
item.username
} < /td> <
td > {
item.password
} < /td> <
/tr>
);
})
} <
/tbody> <
/table> <
/div>
);
}
}

class Form extends React.Component {
render() {
return ( <
div id = "Form" >
<
h3 > Add a new item to the table: < /h3> <
form onSubmit = {
this.props.handleFormSubmit
} >
<
label htmlFor = "username" >
Username:
<
input id = "username"
value = {
this.props.newUsername
}
type = "text"
name = "username"
onChange = {
this.props.handleInputChange
}
/> <
/label> <
label
for = "password" >
Password:
<
input id = "password"
value = {
this.props.newPassword
}
type = "password"
name = "password"
onChange = {
this.props.handleInputChange
}
/> <
/label> <
button type = "submit"
value = "Submit" > Add Item < /button> <
/form> <
/div>
);
}
}

ReactDOM.render( < App / > , document.getElementById('root'));
我预先感谢任何愿意花时间帮助我的人。

最佳答案

更新状态后,您可以将数据保存在本地存储中。并且当应用程序呈现时从 localstorage 获取数据,以便您的数据将保留在浏览器中。

localStorage.setItem("table_data", JSON.stringify(data_array));
const data = JSON.parse(localStorage.getItem("table_data")));
console.log(data)

关于javascript - 刷新时保持状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63689252/

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