You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React开发问题:获取的数据首元素无法在页面渲染

问题解决:大理石描述数据无法渲染到页面

核心问题分析

你代码里的第二个useEffect存在语法错误,导致marbeldescription状态没有正确设置为数据的第一个元素:

// 错误写法
setMarbelDescription(data2)[0];

这里逻辑完全错误——setMarbelDescription是状态更新函数,调用它不会返回可用值,你应该先取data2的第一个元素,再传给状态更新函数。

修正步骤

  1. 修复状态更新的语法错误
    把第二个useEffect里的代码改成:
useEffect(() => {
  client.fetch('*[_type == "marbeldescription"]').then((data2) => {
    // 先取数组第一个元素,再更新状态;加|| {}防止空数组导致状态为undefined
    setMarbelDescription(data2[0] || {});
  });
}, []);
  1. 添加数据加载时的容错处理
    接口请求是异步的,初始状态marbeldescription是空对象,直接访问marbeldescription.price可能在数据加载完成前出现报错,可以用两种方式处理:
  • 方式1:使用可选链操作符
<li style={{color: "white"}}>{marbeldescription?.price}</li>
  • 方式2:条件渲染
{marbeldescription.price && <li style={{color: "white"}}>{marbeldescription.price}</li>}

完整修正后的代码片段

const SectionOne = () => {
  const [marbels, setMarbels] = useState([]);
  const [marbeldescription, setMarbelDescription] = useState({});

  useEffect(() => {
    client.fetch('*[_type == "marbels"]').then((data) => {
      setMarbels(data);
    });
  }, []);

  useEffect(() => {
    client.fetch('*[_type == "marbeldescription"]').then((data2) => {
      setMarbelDescription(data2[0] || {});
    });
  }, []);

  return (
    <div className="bg-dark">
      <section className="steps container-custom">
        <div className="row ">
          <Slider {...settings}>
            {marbels.map((marbel, index) => (
              <div key={index} className="col-12 col-sm-6 d-md-flex justify-content-md-center">
                <div>
                  <img
                    src={urlFor(marbel.imgUrl)}
                    alt="Coffe Flavour"
                  />
                  <p className="text-white">{marbel.name}</p>
                </div>
              </div>
            ))}
          </Slider>
          <div className="col-12 col-sm-6 align-self-center justify-content-md-center text-white">
            <div className="steps__content-width">
              <h1 className="h2 mb-4">Our Marbles</h1>
              <p className="mb-4">
                <ul>
                  <li style={{color: "white"}}>{marbeldescription?.price}</li>
                </ul>
              </p>
            </div>
          </div>
        </div>
      </section>
    </div>
  );
};

export default SectionOne;

内容的提问来源于stack exchange,提问作者isabella-re

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 05:01:24