react state ajax,javascript - React setState doesn't rerender in ajax success - Stack Overflow

本文探讨了在使用AJAX循环渲染组件时,如何正确设置组件状态的问题。作者提到在AJAX回调中直接修改`self`的state会导致预期变化不生效,分享了通过指向组件而非AJAX调用来解决此问题的方法,包括使用Promise和组件内部事件处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

I'm having trouble setting state in an ajax function. An ajax call is looped, and for each iteration a component is rendered, all of which are added to an array. This array will be used to set the state of my component, and then I'll return this.state.toRender as the JSX return which will appear on the DOM.

var self = this;

$.ajax({

success: function(data) {

// generate array of objects

self.setState({toRender: renderArray});

Since JS passes by value, I shouldn't setState of var self, right? Somehow I need to point to the component instead of the ajax call to change the state. A promise didn't seem to have access to the array generated, and I didn't get results using a callback.

The initial state actually goes through the ajax function and returns exactly what I want, but the event (DropDown selection) that is supposed to update state doesn't make any change.

The child component is called in the parent's return:

And in the child component I've added this function:

pick : function(event) {

var selected = event.target.value;

this.setState({list: "all"}, this.props.newSelect('theUrl'));

I know that DropDown selection works because I've used it successfully in earlier stages of the project.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值