Javascript 刷新时保存搜索词
我只是想在刷新/重新加载页面时保存和恢复搜索词(表单数据)。我试过几种解决办法,但都没有用 流:用户提交搜索词,并将其带到Spotify检索accessToken(如果它不可用)。检索accessToken后,将刷新初始页面,但必须重新输入搜索。这不是一个好的用户体验 我得出结论,Web存储是他们的发展方向,当然这不是唯一的途径。我不确定这是否应该归入生命周期方法:componentDidMount()&componentdiddupdate()。也许这太过分了?在任何情况下,我都尝试使用本地存储和会话存储。我的实现显然失败了,因为我没有得到预期的结果。React dev tools显示搜索栏术语的状态,但未保存该术语。同样值得注意的是:React-dev工具显示onSubmit事件处理程序注册为bound(){},而不是预期的bound handleInitialSearchTerm(){}。控制台还显示没有错误 请不要使用第三方图书馆 SearchBar.jsJavascript 刷新时保存搜索词,javascript,reactjs,local-storage,session-storage,Javascript,Reactjs,Local Storage,Session Storage,我只是想在刷新/重新加载页面时保存和恢复搜索词(表单数据)。我试过几种解决办法,但都没有用 流:用户提交搜索词,并将其带到Spotify检索accessToken(如果它不可用)。检索accessToken后,将刷新初始页面,但必须重新输入搜索。这不是一个好的用户体验 我得出结论,Web存储是他们的发展方向,当然这不是唯一的途径。我不确定这是否应该归入生命周期方法:componentDidMount()&componentdiddupdate()。也许这太过分了?在任何情况下,我都尝试使用本地存
import React from 'react';
import "./SearchBar.css";
class SearchBar extends React.Component {
constructor(props) {
super(props);
this.state = {
term: this.handleInitialSearchTerm
};
this.search = this.search.bind(this);
this.handleInitialSearchTerm = this.handleInitialSearchTerm.bind(this);
this.setSearchTerm = this.setSearchTerm.bind(this);
this.handleSearchOnEnter = this.handleSearchOnEnter.bind(this);
this.handleTermChange = this.handleTermChange.bind(this);
}
handleInitialSearchTerm = (event) => {
if (typeof (Storage) !== "undefined") {
if (localStorage.term) {
return localStorage.term
} else {
return this.setSearchTerm(String(window.localStorage.getItem("term") || ""));
}
}
};
setSearchTerm = (term) => {
localStorage.setItem("term", term);
this.setState({ term: term });
}
search() {
this.props.onSearch(this.state.term);
}
handleSearchOnEnter(event) {
if (event.keyCode === 13) {
event.preventDefault();
this.search();
}
}
handleTermChange(event) {
this.setState({
term: event.target.value
});
}
render() {
return (
<div className="SearchBar">
<input
placeholder="Enter A Song, Album, or Artist"
onChange={this.handleTermChange}
onKeyDown={this.handleSearchOnEnter}
onSubmit={this.handleInitialSearchTerm}
/>
<button className="SearchButton" onClick={this.search}>
SEARCH
</button>
</div>
);
}
}
export default SearchBar;
let accessToken;
const clientId = "SpotifyCredentialsHere";
const redirectUri = "http://localhost:3000/";
const CORS = "https://cors-anywhere.herokuapp.com/"; // Bypasses CORS restriction
const Motify = {
getAccessToken() {
if (accessToken) {
return accessToken;
}
// if accessToken does not exist check for a match
const windowURL = window.location.href;
const accessTokenMatch = windowURL.match(/access_token=([^&]*)/);
const expiresInMatch = windowURL.match(/expires_in=([^&]*)/);
if (accessTokenMatch && expiresInMatch) {
accessToken = accessTokenMatch[1]; //[0] returns the param and token
const expiresIn = Number(expiresInMatch[1]);
window.setTimeout(() => accessToken = "", expiresIn * 1000);
// This clears the parameters, allowing us to grab a new access token when it expires.
window.history.pushState("Access Token", null, "/");
return accessToken;
} else {
const accessUrl = `https://accounts.spotify.com/authorize?client_id=${clientId}&response_type=token&scope=playlist-modify-public&redirect_uri=${redirectUri}`;
window.location = accessUrl;
}
},
search(term) {
const accessToken = Motify.getAccessToken();
const url = `${CORS}https://api.spotify.com/v1/search?type=track&q=${term}`;
return fetch(url, { headers: { Authorization: `Bearer ${accessToken}` }
}).then(response => response.json()
).then(jsonResponse => {
if (!jsonResponse.tracks) {
return [];
}
return jsonResponse.tracks.items.map(track => ({
id: track.id,
name: track.name,
artist: track.artists[0].name,
album: track.album.name,
uri: track.uri,
preview_url: track.preview_url
}));
})
}
...
请检查我添加的代码 我所做的改变如下: (一)
从“React”导入React;
导入“/SearchBar.css”;
类SearchBar扩展了React.Component{
建造师(道具){
超级(道具);
此.state={
term:JSON.parse(localStorage.getItem('term'))| |“”;
};
this.search=this.search.bind(this);
this.handleInitialSearchTerm=this.handleInitialSearchTerm.bind(this);
this.setSearchTerm=this.setSearchTerm.bind(this);
this.handleSearchOnEnter=this.handleSearchOnEnter.bind(this);
this.handleTermChange=this.handleTermChange.bind(this);
}
handleInitialSearchTerm=(事件)=>{
if(类型(存储)!=“未定义”){
if(localStorage.term){
返回localStorage.term
}否则{
返回此.setSearchTerm(字符串(window.localStorage.getItem(“术语”)| |“”);
}
}
};
setSearchTerm=(术语)=>{
这是我的国家({
任期:任期
},
() => {
setItem('term',JSON.stringify(this.state.term));
}
搜索(){
this.props.onSearch(this.state.term);
}
HandleSearchOnter(事件){
如果(event.keyCode===13){
event.preventDefault();
这是search();
}
}
handleTermChange(事件){
这是我的国家({
术语:event.target.value
});
}
render(){
报税表(<
div className=“搜索栏”>
<
input placeholder=“输入歌曲、专辑或艺术家”
onChange={
这是我的零钱
}
onKeyDown={
这是我的手机
}
onSubmit={
此.handleInitialSearchTerm
}
/> <
按钮className=“SearchButton”
onClick={
这是搜索
} >
搜寻<
/按钮><
/div>
);
}
}
导出默认搜索栏;
请检查我添加的代码 我所做的改变如下: (一)
从“React”导入React;
导入“/SearchBar.css”;
类SearchBar扩展了React.Component{
建造师(道具){
超级(道具);
此.state={
term:JSON.parse(localStorage.getItem('term'))| |“”;
};
this.search=this.search.bind(this);
this.handleInitialSearchTerm=this.handleInitialSearchTerm.bind(this);
this.setSearchTerm=this.setSearchTerm.bind(this);
this.handleSearchOnEnter=this.handleSearchOnEnter.bind(this);
this.handleTermChange=this.handleTermChange.bind(this);
}
handleInitialSearchTerm=(事件)=>{
if(类型(存储)!=“未定义”){
if(localStorage.term){
返回localStorage.term
}否则{
返回此.setSearchTerm(字符串(window.localStorage.getItem(“术语”)| |“”);
}
}
};
setSearchTerm=(术语)=>{
这是我的国家({
任期:任期
},
() => {
setItem('term',JSON.stringify(this.state.term));
}
搜索(){
this.props.onSearch(this.state.term);
}
HandleSearchOnter(事件){
如果(event.keyCode===13){
event.preventDefault();
这是search();
}
}
handleTermChange(事件){
这是我的国家({
术语:event.target.value
});
}
render(){
报税表(<
div className=“搜索栏”>
<
input placeholder=“输入歌曲、专辑或艺术家”
onChange={
这是我的零钱
}
onKeyDown={
这是我的手机
}
onSubmit={
此.handleInitialSearchTerm
}
/> <
按钮className=“SearchButton”
onClick={
这是搜索
} >
搜寻<
/按钮><
/div>
);
}
}
导出默认搜索栏;
localStorage.term
??trylocalStorage.getItem(..
-更新/更改时未保存值-setSearchTerm
未从处理程序调用localStorage.term
??trylocalStorage.getItem(..
-更新/更改时未保存值-setSearchTerm
未从处理程序调用
this.state = {
term: JSON.parse(localStorage.getItem('term')) || '';
};
setSearchTerm = (term) => {
this.setState({
term: term
},
() => {
localStorage.setItem('term', JSON.stringify(this.state.term)));
}