我目前正在用React构建一个简单的应用程序,而且我对它还比较陌生,所以我觉得我的解决方案很简单,只是我还没有看到它的经验。
基本上,这个应用程序允许用户输入世界上任何城市的名称,输出会更新输入下的React实时时钟组件。为此,我使用城市时区库来获取用户所需城市的数据,使用moment.js将城市时间解析为所需时区,当然,还使用React实时时钟向用户显示实际时间。
在我的loadTime
函数中,我检索了timezone属性,并将其传递给moment().tz()
方法进行解析。在我将state
传入setState()
并将更新后的状态打印到控制台之后,它确实显示了正确的状态。例如,用户键入Tokyo,返回键/值timezone: "Asia/Tokyo"
。
我的问题是,在将this.state.timezone
传递给我的React实时时钟组件timezone
属性并单击Get time按钮后,我的时钟实际上并没有更新状态,而是保持用户浏览器的当前时间。
我已经确定我的loadTime()
函数按照它应该的方式工作,所以我相信我的时钟组件没有正确地连接到读取更新的timezone
状态。另一种可能性,正如我的问题中所说的,是我错误地使用了setState()
。
这里有没有我忽略的地方,或者我在滥用setState()
的问题上走对了路?
import Moment from 'moment-timezone';
import cityTimezones from 'city-timezones';
import Clock from 'react-live-clock';
let moment = require('moment-timezone');
export default class Search extends Component {
state = {
userLocation: "",
localTime: "",
rows: [],
};
//Methods
loadTime = (searchTerm) => {
const city = cityTimezones.lookupViaCity(searchTerm);
let state = this.state;
if (city.length > 0) {
const timezone = city[0].timezone;
let now = moment().tz(timezone).format('h:mm:ss a');
state.localTime = now;
state.timezone = timezone;
} else {
state.userLocation = "";
state.localTime = "";
};
this.setState(state);
console.log(state);
};
handleChange = (e) => {
let state = this.state;
state[e.target.name] = e.target.value;
this.setState(state);
}
//Create
handleClick = (e) => {
e.preventDefault();
this.loadTime(this.state.userLocation);
};
render () {
let alert = (!this.state.localTime) ? "Please enter location": "";
return (
<div className="search-container-fluid gradient p-3">
<div className="row">
<div className="search-container">
<input onChange={this.handleChange} name="userLocation" type="text"
className="form-control" placeholder="Enter a location" />
<button onClick={this.handleClick} name="search-btn" className="btn btn-search"
type="button" >Get time.</button>
<div className="output-container mt-5">
<Clock ticking={true} format={'hh:mm:ss a'} timezone={this.state.timezone} />
{/* {alert} */}
</div>
</div>
</div>
</div>
)
}
};```
发布于 2020-02-04 02:51:20
在这里,由于react无法识别更改,您将直接操作状态,请尝试使用以下代码
//Methods
loadTime = (searchTerm) => {
const city = cityTimezones.lookupViaCity(searchTerm);
let state = {...this.state};
if (city.length > 0) {
const timezone = city[0].timezone;
let now = moment().tz(timezone).format('h:mm:ss a');
state.localTime = now;
state.timezone = timezone;
} else {
state.userLocation = "";
state.localTime = "";
};
this.setState(state);
console.log(state);
};
handleChange = (e) => {
let state = {...this.state};
state[e.target.name] = e.target.value;
this.setState(state);
}
https://stackoverflow.com/questions/60048458
复制相似问题