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

使用React Context API开发天气应用报TypeError: render is not a function如何解决

错误成因

你对第三方库use-turkey-cities的调用方式不符合官方规范,该库的默认导出不是React自定义Hook,而是采用Render Props模式封装的 React 组件。你直接将它作为函数调用获取cities、city属性的操作不符合预期,导致渲染逻辑抛出类型错误。

解决方案

方案1:按照库的规范使用Render Props模式

修改SelectCity.js代码如下:

import {useContext} from 'react'
// 重命名更符合组件的命名规范
import TurkeyCities from "use-turkey-cities"
import CityContext from '../context/CityContext'

function SelectCity() {
    const { contextCity, setContextCity } = useContext(CityContext)

    return (
        <div>
            {/* 通过render属性接收库返回的城市数据 */}
            <TurkeyCities 
                render={({ cities, city }) => (
                    <select
                        onChange={e => {
                            setContextCity(e.target.value);
                        }}
                        {/* 建议替换为contextCity保持状态同步,无需依赖库内部状态 */}
                        value={contextCity || city}
                    >
                        {cities.map(city => (
                            <option key={`city-${city}`} value={city}>
                                {city}
                            </option>
                        ))}
                    </select>
                )}
            />
        </div>
    )
}

export default SelectCity

方案2:不依赖第三方库,自行封装城市数据Hook

如果不需要额外能力,可以直接自己维护土耳其城市列表,更灵活可控:

  1. 先卸载use-turkey-cities库:npm uninstall use-turkey-cities
  2. 新建hooks/useTurkeyCities.js文件:
import { useState } from 'react'
// 可根据需求补充完整城市列表
const TURKEY_CITIES = ['Istanbul', 'Ankara', 'Izmir', 'Bursa', 'Antalya']

export default function useTurkeyCities() {
  const [city, setCity] = useState(TURKEY_CITIES[0])
  return {
    cities: TURKEY_CITIES,
    city,
    setCity
  }
}
  1. 原有SelectCity.js的Hook调用逻辑无需修改,仅需要替换import路径为自己封装的Hook路径即可。

内容的提问来源于stack exchange,提问作者noname

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 13:45:05