简体   繁体   中英

How to update React localstorage?

I have a website that does one of two things. If you have never been to the site, it asks for info, which is stored in localstorage, and then it takes you to the main content. If you have filled out the info before, then it takes you straight to the main content. This is all done in one page.

Currently, my main content page only works upon page reload. This is because React does not have localstorage data to load the main content. It is only rendering the page on load. As stated, this is all to happen on the same page.

<script type="text/babel">
var Weatherapp = React.createClass({

render: function(){
var weatherplace = localStorage.getItem('yourlocation');
var weatherplaceshared = localStorage.getItem('yourlocation').replace(/,/g, ", ");
var weathervane = new XMLHttpRequest();
weathervane.open('GET', 'http://api.openweathermap.org/data/2.5/weather?q='+weatherplace+'&appid=stuff', false);
weathervane.send(null);
var runthru = JSON.parse(weathervane.response);
var weathervalue = runthru.main.temp;
var weatherimage = runthru.weather[0].icon;
var weatherimageplace = "http://openweathermap.org/img/w/"+weatherimage+".png";
return (
<div id="weatherapp_container">

<div id="weatherapp_location">{weatherplaceshared}</div>
<div id="weatherapp_icon"><img src={weatherimageplace}/></div>
<div id="weatherapp_temperature"><p>{weathervalue}&deg;F</p></div>


</div>
)}

});

ReactDOM.render(<Weatherapp />, document.getElementById('weatherapp'));
</script>

I want to restart the render function on a click event. To that end, I have changed my code like so. Note, the submitsuestado is the button that activates my function once input is stored for the first time.

render: function(){
document.getElementById('submitsuestado').addEventListener('click', function(){
var yourcity = document.getElementById('suciudad').value;
var yourstate = document.getElementById('suestate').value;
localStorage.setItem('yourlocation', yourcity+","+yourstate);

From there I duplicate the rest of the code on top. However, this does not work. I am trying to understand where the error lies, and what I might do to make sure that Weatherapp runs both on page load with local storage data stored, as well as on a fresh page where the local storage data is just recently put.

your click event just save value into localstorage, it didn't change the state of your component, so react will not render. if your want to render your component, just try to put your button into your component, and use setState to change the state of your component.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM