简体   繁体   English

反应功能组件 - 渲染子 - null 属性

[英]react functional component - render child - null property

i've got a problem with functional components and passing a service to child component I created a SoundAlarmService:我在功能组件和将服务传递给子组件时遇到问题我创建了一个 SoundAlarmService:

import { Audio } from 'expo-av';
class SoundAlamarService {

static readonly defaultSoundPath = require('../assets/1.wav');

private audioSound:Audio.Sound;


static CreateAsync = async(soundAsset = this.defaultSoundPath)=>{
    const {sound} = await Audio.Sound.createAsync(soundAsset);
    return new SoundAlamarService(sound);
}

private constructor(sound:Audio.Sound) {
    this.audioSound = sound;
}

play = async()=>{
    await this.audioSound.playAsync();
}

stop = async()=>{
    await this.audioSound.stopAsync(); 
}
}

export default SoundAlamarService;

and i creating it by useEffetct (tried once, but also not working) and then want to pass it to child component我通过 useEffetct 创建它(尝试过一次,但也没有工作)然后想将它传递给子组件

export const MainTimer = () => {
  let alarmService:SoundAlarmService | null = null;
  const [initialized, setInitialized] = useState(false);

  useEffect(()=>{
     SoundAlarmService.CreateAsync().then(result=>{
      alarmService = result;
      setInitialized(true);
    })
  })
 
return !initialized 
  ? <></> 
  : (
    <View style={styles.container}>
         {timeConfired ? 
      <MainTimerAlarm soundService={alarmService} setTime={setTime} time={time} timeInfo={timer} stopped={!timeConfired} /> 
      :<></>}
      <SetMainTimer setTimer={setTimerFunc} setCancel={setCancel} />

    </View>
  ); 
}

i can debug and see it is assigned on UseEffect, but then on render method it is null how to fix that?我可以调试并看到它是在 UseEffect 上分配的,但是在渲染方法上它是 null 如何解决这个问题?

timeConfired is not defined hence it is taking as null. Defining this variable in state and separating MainTimerAlarm from the functional component and rendering in a separate components will work. timeConfired 未定义,因此它取为 null。在 state 中定义此变量并将 MainTimerAlarm 与功能组件分开并在单独的组件中呈现将起作用。

just moved declatarion of alarm service above functional component刚刚将警报服务的声明移动到功能组件上方

let alarmService:SoundAlarmService;
export const MainTimer = () => {

  const [initialized, setInitialized] = useState(false);

  useEffect(()=>{
     SoundAlarmService.CreateAsync().then(result=>{
      alarmService = result;
      setInitialized(true);
    },[])
  })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM