gpt4 book ai didi

javascript - 当reactjs中的变量更新时,以及如何强制更新

转载 作者:行者123 更新时间:2023-12-01 03:42:39 26 4
gpt4 key购买 nike

我试图理解,我知道当我 console.log(图片) 时我得到最终结果

当我“console.log(JSON.stringify(pictures))”时,我得到了当前的那一刻。

为什么在记录第二个选项时,数组是空的最后它得到了一个值,

如何强制值与 this.state 同步

问题是当我最后发送时:

ImageList pics={this.state.picturesArr} />

它被发送为空

let pictures = [];
let urls =[];
let titles=[];
let nextpage ='';
let pageback='';

class App extends Component {

constructor(props) {
super(props);

this.state = {
picturesArr: [],
urlArr: [],
titleArr:[],
nextPage:'',
prevuisPage:''
};

this.loadSubreddit = this.loadSubreddit.bind(this);
}

loadSubreddit(subre) {

reddit.hot(subre).limit(5).fetch(function(res) {
console.log(res);
nextpage = res.data.after.toString();
// pageback = res.data.before.valueOf();

for (let i = 0; i < res.data.children.length; i++){
pictures.push(res.data.children[i].data.url);
urls.push(res.data.children[i].data.permalink);
titles.push(res.data.children[i].data.title);
}
});

this.setState({
picturesArr: pictures,
urlArr: urls,
titleArr: titles,
nextPage: nextpage,
prevuisPage: pageback
}, () => {
console.log(this.state)
});

console.log(pictures);
console.log(JSON.stringify(pictures));
}


componentWillMount() {
console.log('comp is mounting');
this.loadSubreddit('cats');
}

render() {
return (
<div className="App">
<div className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h2>Welcome to React</h2>
</div>
<Col sm={8} md={10} smOffset={2} mdOffset={1} >
<ImageList pics={this.state.picturesArr} />
</Col>
</div>
);
}
}

export default App;

最佳答案

在您提供的代码中,您在 api 调用回调之外调用 this.setState

您需要 (1) 将用于设置状态的代码移至回调内部,并 (2) 将回调函数绑定(bind)到组件实例以访问其 this.setState

固定的 loadSubbreddit 函数如下所示。

loadSubreddit(subre) {

reddit.hot(subre).limit(5).fetch(function(res) {
console.log(res);
nextpage = res.data.after.toString();
// pageback = res.data.before.valueOf();

for (let i = 0; i < res.data.children.length; i++){
pictures.push(res.data.children[i].data.url);
urls.push(res.data.children[i].data.permalink);
titles.push(res.data.children[i].data.title);
}

this.setState({
picturesArr: pictures,
urlArr: urls,
titleArr: titles,
nextPage: nextpage,
prevuisPage: pageback
}, () => {
console.log(this.state)
});

console.log(pictures);
console.log(JSON.stringify(pictures));
}.bind(this));
}

关于javascript - 当reactjs中的变量更新时,以及如何强制更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43762861/

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