javascript - ajax 调用后无法接收更新的 props( react )

标签 javascript ajax reactjs

获取向服务器发送数据的函数

addRemark(id,e) {

      var remarktext = this.state.popUpText;
      this.props.addRemark(id,remarktext); // this func sends to serve
      this.props.closePopUp();
      setTimeout(function() { this.props.IncomeListProfile(); }.bind(this), 1000);
    }

现在我正在等待使用此代码更新我的列表
setTimeout(function() { this.props.IncomeListProfile();

但我现在想清楚,何时添加数据。我在行动中创建了 func

export function SendedData(data) {
if (data) {
  return {
      type: SENDED_REMARK, data:true
        }
}
}

在那里我收到了 TRUE。当要求好时

function mapStateToProps(state) {


      var sended = state.getIn(['PopupReducer'])['sendedRemark'];
      console.log(sended + 'true');
      return {

        sended: sended
            };

  }

但是在发送请求后我无法获得真实值,在我尝试做的组件中

componentWillReceiveProps(nextProps) {
        this.setState({ sendeder: nextProps.sended });
        console.log('isshwon!!!! ' + this.state.sendeder); //get false every time
      }

所以想法是,当我按下“保存”按钮时,我将请求发送到服务器,得到 TRUE 响应,然后我需要更新我的列表

我使用 axios 的请求

export function addRemark(id,remarktext) {

    return dispatch => {

        return (
            console.log(id + remarktext),

            axios.post(Api.getURI("addremark"),{body: {course_id:id, remark:remarktext}}, {
            headers: { 'X-Authenticated-Userid': '15000500000@1' }
         }).then(function (response) {


                    //console.log(response.data);
                    dispatch(SendedData(response.data));

                })
            .catch((error) => {
                        console.log(error);
                })
            )
    }

}

最佳答案

你的 reducer

[types.SENDED_DATA] : (state, action) => 
   return { ...state,
      data: Immutable.fromJS(action.d),ata
      isLoading: false
   }

您的组件

shouldComponentUpdate (nextProps) {
    return nextProps.data !== this.props.data
}

componentDidUpdate (prevProps) {
    if(prevProps.data !== this.props.data) {
       //do smthing that you need, data was changed
      this.props.IncomeListProfile();
    }
}

或者简单地对重新渲染组件不执行任何操作,该组件基于data进行渲染,因为shouldComponentUpdate返回true - 它将重新渲染

关于javascript - ajax 调用后无法接收更新的 props( react ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42111905/

相关文章:

reactjs - React、Redux 和不可变

javascript - Postman 中的外部库

javascript - IE 上新 XMLHttpRequest() 的 JS Ajax 未指定错误

javascript - 带有参数和成功回调的 Angular 服务工厂

javascript - 检索ajax post请求发送的数据

ajax - MVC 5无效的JSON原语

javascript - Reactjs/Javascript 更新对象键名

visual-studio - 改进 Visual Studio 2017 中的 JSX 编辑

javascript - 在数组中查找最佳路线和价格

javascript - 测试localStorage是否已满