render中调用的函数返回undefined。

huangapple go评论65阅读模式
英文:

function called in render return undefined

问题

以下是您要翻译的内容:

"I passed my last 2 days to fix a little problem in my React project (builded with ViteJs, react-router.. and Strapi backEnd) but I need your help !

The case is: I have an images gallery component with a precise structure and images called with an API request to Strapi and saved in an array. I decide to create a function to check in the array if one of this elements contain a specific name and if it's true send back the URL image.

Finally on my webpage I've an URL with "undefined" but on the function my console.log contain the good URL !

Thanks a lot for any help or suggest, I hope all elements are clear but if need more details, ask me render中调用的函数返回undefined。


const myFunc = (type) => {
   data[0]?.attributes?.collection?.data.map((el) => { 
       if (el.attributes.name === type) {
          console.log("THIS IS MY URL :", el?.attributes?.url);
          return el.attributes.url
       } else { return } 
   }
}
   
return (
    ... 
    <div className="categoriesFrame">
        <div className="col">
            <div className="row">
                <img
                    src={import.meta.env.VITE_APP_UPLOAD_URL + myFunc("sale")}
                    alt=""
                />
                <button>
                    <Link className="link" to="/products/0">
                        Sale
                    </Link>
                </button>
            </div>
            <div className="row">
                <img
                    src={import.meta.env.VITE_APP_UPLOAD_URL + myFunc("women")}
                    alt=""
                />
                <button>
                    <Link className="link" to="/products/1">
                        Women
                    </Link>
                </button>
            </div>
        </div>
    </div>
    ...
    // With another div.col and row to make this specific structure.
)

I've design an specific frame for a gallery images and this images come from my API request. I just want to match each picture.url to is correct position in the frame. In the function "myFunc" I tried to create an useState to store the URL inside but it makes an infinite loop and nothing is re-render in front :/

I tried to put an async/await in the function but now in the render it appears "[object Promise]"
"

英文:

I passed my last 2 days to fix a little problem in my React project (builded with ViteJs, react-router.. and Strapi backEnd) but I need your help !

The case is : I have an images gallery component with a precise structure and images called with an API request to Strapi and saved in an array.
I decide to create a function to check in the array if one of this elements contain a specific name and if it's true send back the URL image.

Finally on my webpage I've an URL with "undefined" but on the function my console.log contain the good URL !

Thanks a lot for any help or suggest, I hope all elements are clear but if need more details, ask me render中调用的函数返回undefined。


const myFunc = (type) =&gt; {
   data[0]?.attributes?.collection?.data.map((el) =&gt; { 
       if (el.attributes.name === type) {
          console.log(&quot;THIS IS MY URL :&quot;, el?.attributes?.url);
          return el.attributes.url
       } else { return } 
   }
}
   
return (
    ... 
    &lt;div className=&quot;categoriesFrame&quot;&gt;
        &lt;div className=&quot;col&quot;&gt;
            &lt;div className=&quot;row&quot;&gt;
                &lt;img
                    src={import.meta.env.VITE_APP_UPLOAD_URL + myFunc(&quot;sale&quot;)}
                    alt=&quot;&quot;
                /&gt;
                &lt;button&gt;
                    &lt;Link className=&quot;link&quot; to=&quot;/products/0&quot;&gt;
                        Sale
                    &lt;/Link&gt;
                &lt;/button&gt;
            &lt;/div&gt;
            &lt;div className=&quot;row&quot;&gt;
                &lt;img
                    src={import.meta.env.VITE_APP_UPLOAD_URL + myFunc(&quot;women&quot;)}
                    alt=&quot;&quot;
                /&gt;
                &lt;button&gt;
                    &lt;Link className=&quot;link&quot; to=&quot;/products/1&quot;&gt;
                        Women
                    &lt;/Link&gt;
                &lt;/button&gt;
            &lt;/div&gt;
        &lt;/div&gt;
    &lt;/div&gt;
    ...
    // With another div.col and row to make this specific structure.
)

     

I've design an specific frame for a gallery images and this images come from my API request. I just want to match each picture.url to is correct position in the frame.
In the function "myFunc" I tried to create an useState to store the URL inside but it makes an infinite loop and nothing is re-render in front :/

I tried to put an async/await in the function but now in the render it appears "[object Promise]"

答案1

得分: 2

由于您在箭头函数中使用了{},隐式返回不起作用。
您需要明确返回该值,例如:

const myFunc = (type) => {
  // 请注意下面的返回语句。
  return data[0]?.attributes?.collection?.data.map((el) => {
    if (el.attributes.name === type) {
      console.log('THIS IS MY URL :', el?.attributes?.url);
      return el.attributes.url;
    } else {
      return;
    }
  });
};

此外,您没有正确使用.map.map基于您从回调函数中返回的值创建一个新数组。在条件不匹配的情况下,您返回的是undefined。因此,这将创建一个包含未匹配条件的未定义值的数组。
在这种情况下使用.map的另一个问题是它返回一个数组。无论您的映射函数如何正常工作,根据您的HTML,您的src URL字符串始终会附加[object Array]

最好使用.find方法(假设只有一个匹配项):

const myFunc = (type) => {
  const typeAttr = data[0]?.attributes?.collection?.data.find(
    (el) => el.attributes.name === type
  );
  return typeAttr ? typeAttr.attributes.url : '';
};
英文:

Since you're using a { with the arrow function, the implicit return would not work.
You need to explicitly return the value. such as

const myFunc = (type) =&gt; {
// notice the return statement below.
return data[0]?.attributes?.collection?.data.map((el) =&gt; {
if (el.attributes.name === type) {
console.log(&#39;THIS IS MY URL :&#39;, el?.attributes?.url);
return el.attributes.url;
} else {
return;
}
});
};

Additionally, you're not using .map in correct way. .map creates a new array based on the value you return from your callback function. The instances where your condition doesn't match, you're returning undefined. So this will create an array that has undefined values where the condition did not match.
Another problem with using .map in this is that it returns an array. so no matter how correctly your map function works, based on your html, you'd always get [object Array] appended to your src url string.

The best would be to use .find method (assuming you have only one match)

const myFunc = (type) =&gt; {
const typeAttr = data[0]?.attributes?.collection?.data.find(
(el) =&gt; el.attributes.name === type
);
return typeAttr ? typeAttr.attributes.url : &#39;&#39;;
};

huangapple
  • 本文由 发表于 2023年3月3日 18:24:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/75625863.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定