在下面的代码中,当我更改输入文本时,localStorage不会保存最后一个符号。好像我写qwerty,刷新它只给qwert。
user.addProjects(project).then(function(res){});
答案 0 :(得分:1)
这是一个已知问题。您正在使用state
事件更新onChange
。但是您在没有设置状态的情况下使用this.state.name
。由于setState
为async
,因此请尝试使用state
中的callback
值,如下所示。
changeName(e){
var _this = this;
this.setState({name: e.target.value}, function(){
localStorage.setItem('username', _this.state.name);
});
},
或强>
只需使用event.target.value
存储在localStoarge
changeCity(e){
this.setState({city: e.target.value}); //here state.name != e.target.value
localStorage.setItem('city', e.target.value);
},
答案 1 :(得分:0)
setState
不会自动更新React中的状态对象。您可以在localStorage存储时使用target.value
。
changeName(e){
this.setState({name: e.target.value})
localStorage.setItem('username', e.target.value)
},
查看React Documentation了解详情
答案 2 :(得分:0)
请参阅React.js docs:
setState()不会立即改变this.state,但会创建挂起状态转换。在调用此方法后访问this.state可能会返回现有值。
要解决此问题,您可以将回调传递给class Request {
RequestStreamer* streamer;
int contentLen;
public:
Request()
{
contentLen = 0;
streamer = new RequestStreamer(this);
}
~Request()
{
delete streamer;
}
int getContentLen()
{
return contentLen;
}
bool initialize ()
{
// Code to update 'contentLen' by reading from source request object.
// <code>
if (streamer) streamer->initialize();
}
bool sendReq()
{
streamer->streamReq();
}
int getBytes (int nBytes)
{
// some code to read nBytes from the input source of this request object
}
};
class RequestStreamer {
Request* req;
bool bEnabled;
int chunkSize;
public:
RequestStreamer(Request* aobj)
{
chunkSize = 1024*1024;
req = aobj;
}
~RequestStreamer()
{
}
bool initialize()
{
if (req && req->getContentLen() > chunkSize)
bEnabled = true;
}
bool streamReq()
{
if (!req) return false;
// Assume that there exists socket object implementation already
if (bEnabled)
{
while (req->getBytes(chunkSize) != -1)
socket->send(req->getBytes(chunkSize));
}
else
{
socket->send(req->getBytes(req->getContentLen()));
}
}
};
或使用setState
:
componentDidUpdate