嵌套对象的promise.then()中的响应未定义

时间:2020-02-24 15:29:08

标签: reactjs typescript react-redux axios redux-thunk

我在Redux分派中遇到奇怪的行为。对于分派功能res未定义,但是对于控制台日志,该功能调用res上方的一行被正确记录。任何想法为什么会发生这种情况?

主要动作

myJsonObject = myReplace(myJsonObject, "aKey", "newValue"); // I know,  the assignement could be done in the method, too.

成功操作

     static async Task Main(string[] args)

    {
        int Flag = 0;


        //  var message = await result;

        try
        {


            var tenantId = "XXXXX.onmicrosoft.com";
            string searchCriteria = "";
            string searchString = "";

            string tokenUrl = $"https://login.microsoftonline.com/XXXXX.onmicrosoft.com/oauth2/v2.0/token";
            var tokenRequest = new HttpRequestMessage(HttpMethod.Post, tokenUrl);

            //I am Using client_credentials as It is mostly recommended
            tokenRequest.Content = new FormUrlEncodedContent(new System.Collections.Generic.Dictionary<string, string>
            {
                ["grant_type"] = "client_credentials",
                ["client_id"] = "XXX9",
                ["client_secret"] = "XXXXXX",
                ["scope"] = "https://graph.microsoft.com/.default"
            });

            dynamic json;
            AccessTokenClass results = new AccessTokenClass();


            //New Block For Accessing Data from Microsoft Graph Rest API
            HttpClient client = new HttpClient();
            var tokenResponse = await client.SendAsync(tokenRequest);
            json = await tokenResponse.Content.ReadAsStringAsync();
            results = JsonConvert.DeserializeObject<AccessTokenClass>(json);

            HttpClient _client = new HttpClient();

            string urlGraphUsers = "https://graph.microsoft.com/v1.0/users?$top=999";
            // odata_nextlink
            do
            {
                HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, string.Format(urlGraphUsers));
                //Passing Token For this Request
                request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", results.access_token);
                //unable to get department name in response

                HttpResponseMessage response = await _client.SendAsync(request);
                string responseBody = await response.Content.ReadAsStringAsync();

                dynamic objGpraphUserList = JsonConvert.DeserializeObject<dynamic>(await response.Content.ReadAsStringAsync());


                var apiResponse = await response.Content.ReadAsStringAsync();


                var data = JsonConvert.DeserializeObject<jsonModel>(apiResponse);
                urlGraphUsers = data.odata_nextLink;




                foreach (valueModel r in data.value.ToList())

                {
                   //Print all the fields ,but unable to get Reporting Manager name and Department 
                   Console.WriteLine(r.displayName);
                    Console.WriteLine(r.mail);
                }

                if (Flag == 0)
                {
                    await context.PostAsync($"No Search results found! Please Try again");

                }
            }
            while (urlGraphUsers != null);

        }


        catch
        {
            await context.PostAsync($"Unknown Exception Occurred. Unable to search results!");
            context.Done(true);
        }

        Console.WriteLine(Flag);
        Console.WriteLine("Flag");
        context.Done(true);

    }


     public class jsonModel
    {
        public string @odata_context { get; set; }
        public string @odata_nextLink { get; set; }
        public List<valueModel> value { get; set; }
    }
    public class valueModel
    {
        public List<string> businessPhones { get; set; }
        public string displayName { get; set; }
        public string givenName { get; set; }
        public string jobTitle { get; set; }
        public string mail { get; set; }
        public string mobilePhone { get; set; }
        public string officeLocation { get; set; }
        public string preferredLanguage { get; set; }
        public string surname { get; set; }
        public string userPrincipalName { get; set; }
        public string id { get; set; }
    }

1 个答案:

答案 0 :(得分:0)

如果对象引用丢失,则只需传入值即可。另外,检查传递给dispatch的值-它必须是一个对象(请参见https://redux.js.org/api/store/#dispatchaction

export const uploadFiles = (files: File[], artworkId: string, fileType: string) => (
    (dispatch: Dispatch) => {
        files.forEach(file => {
            axios.post(
                `${my-api-route}, convertToFormDataFile(file, fileType))
                .then(res => {
                    console.log('I got called!)
                    console.log(res)
                    console.log(res.data.data.id) //works
                    const id = res.data.data.id
                  const toDispatch = uploadFileLimitedEditionSuccess(id, file, fileType)
                  console.log(toDispatch)
                  dispatch(toDispatch)
                }) //does not work
                .catch(err => {
               console.log(err)
dispatch(uploadFileLimitedEditionFailure(err.response.data.errors[fileType === 'pdf' ? 'pdf' : 'file'], file.name, fileType))
          })
        })
    }
);