React Native自定义函数timeToString未被识别为函数问题求助
解决React Native中
timeToString函数未被识别的问题 嘿,我来帮你搞定这个报错!你遇到的"该函数不是函数"问题,主要是两个小细节没处理好,咱们一步步来修复:
问题出在哪?
setTimeout里的this跑丢了:在类组件的loadItems方法里,setTimeout的回调函数会改变this的指向,导致它找不到组件实例上的timeToString方法。- 直接修改
state踩坑了:你代码里直接对this.state.items做赋值操作,这不符合React的状态更新规则,不仅可能引发报错,还会让组件渲染出问题。
两种修复方案任你选
方案1:用箭头函数保住this,正确更新状态
把setTimeout的回调改成箭头函数,同时用setState来更新状态,别直接碰this.state:
loadItems(day) { setTimeout(() => { // 先复制一份当前的items,避免直接修改原状态 const newItems = {...this.state.items}; for (let i = -15; i < 85; i++) { const time = day.timestamp + i * 24 * 60 * 60 * 1000; const strTime = this.timeToString(time); if (!newItems[strTime]) { newItems[strTime] = []; const numItems = Math.floor(Math.random() * 5); for (let j = 0; j < numItems; j++) { newItems[strTime].push({ name: `Item for ${strTime}`, height: Math.max(50, Math.floor(Math.random() * 150)), }); } } } // 用setState更新状态,让React正确触发渲染 this.setState({ items: newItems }); }, 1000); }
方案2:在构造函数里绑定this
如果你习惯用普通函数当回调,就在构造函数里把loadItems的this绑定好:
constructor(props) { super(props); this.state = { items: {}, }; // 把loadItems的this绑定到组件实例 this.loadItems = this.loadItems.bind(this); } loadItems(day) { setTimeout(function() { const newItems = {...this.state.items}; for (let i = -15; i < 85; i++) { const time = day.timestamp + i * 24 * 60 * 60 * 1000; const strTime = this.timeToString(time); if (!newItems[strTime]) { newItems[strTime] = []; const numItems = Math.floor(Math.random() * 5); for (let j = 0; j < numItems; j++) { newItems[strTime].push({ name: `Item for ${strTime}`, height: Math.max(50, Math.floor(Math.random() * 150)), }); } } } this.setState({ items: newItems }); }.bind(this), 1000); // 或者在这里绑定this也能行 }
小提醒
- 绝对不要直接修改
this.state,必须通过setState方法更新,这样React才能准确追踪状态变化并重新渲染组件。 - 箭头函数会自动继承外层的
this,在类组件的异步回调里用它,能省不少绑定this的麻烦。
内容的提问来源于stack exchange,提问作者Obisi7
相关产品推荐
相关产品推荐

