在无穷循环中进行代码锁定锁定-不涉及while循环 [英] React code locking in endless loop - no while loops involved

查看:132
本文介绍了在无穷循环中进行代码锁定锁定-不涉及while循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

React有点新,并在下面编写了这段代码.下面的组件用于渲染故事的时间和日期选择器".时间和日期选择器仅针对计划显示该故事的社交媒体进行渲染.

Am a bit new to React and wrote this code below. The component below is for rendering a Time and Date Picker for a tale. The time and date pickers only render for those social media where the tale is scheduled to appear.

class TaleScheduler extends Component {
  constructor(props) {
    super(props);
    this.state = {
      returnData: {},
      totalNeeded: numberOfChannels(this.props.data)
    };
  }
  setSchedule = (date, channel) => {
    const returnData = update(this.state.returnData, {
      $merge: {channel: date}
    })
    this.setState({returnData: returnData})
    const { data, ScheduleTale } = this.props
    if (Object.values(this.state.returnData).length === this.state.totalNeeded) {
      FireAction(this.state.returnData, data.id)
    }
  }
  render() {
    const { data } = this.props
    return (
      <div style={{"display": "inline-block"}}>
        {data.showOnFacebook ? (<DateTimePicker data={data} image={facebook} setSchedule={this.setSchedule} />) : null}
        {data.showOnTwitter? (<DateTimePicker data={data} image={instagram} setSchedule={this.setSchedule} />) : null}
        {data.showOnInstagram ? (<DateTimePicker data={data} image={twitter} setSchedule={this.setSchedule} />) : null}
        {data.showOnApp ? (<DateTimePicker data={data} image={app} setSchedule={this.setSchedule} />) : null}
        <FlatButton label="Schedule" onClick={this.setSchedule} />
      </div>
    )
  }
}

这将根据故事的显示位置渲染一组时间和日期选择器.下面是正在显示的组件

This renders a set of time and date pickers based on where the tale is to be displayed. Below is the component that is being displayed

class DateTimePicker extends Component {
  constructor(props) {
    super(props);
    this.state = {
      date: null,
      time: null
    };
  }
  handleDateInput = (event, date) => {
    this.setState({
      date: date
    })
  }
  handleTimeInput = (event, time) => {
    this.setState({
      time: time
    })
  }
  componentDidUpdate(prevProps, prevState) {
    const {setSchedule, channel} = this.props
    if (this.state.date && this.state.time) {
      setSchedule(concatenateDateAndTime(this.state.date, this.state.time), channel)
    }
  }
  render() {
    return (
      <List>
        <ListItem
        leftAvatar={
          <img src={this.props.image} style={styles.scheduledChannelImgStyle} />
        }>
        </ListItem>
        <ListItem>
          <DatePicker onChange={this.handleDateInput} />
        </ListItem>
        <ListItem>
          <TimePicker onChange={this.handleTimeInput} />
        </ListItem>
      </List>
    )
  }
}

同时选择上面的日期和时间.整个页面锁定在一个无限循环中,导致页面冻结.我确信这些函数在循环中互相调用.但是我对React渲染还不了解,无法确切地找出原因.

On selecting both the date and the time above. The entire page locks into an endless loop that caused the page to freeze. I am sure the functions are being calling each other in loop. But I do not know enough about React rendering to be able to figure out exactly why.

推荐答案

componentDidUpdate中,在调用函数之前检查previous date and time state values,否则在定义日期和时间并且组件正在更新时将调用它.每当您调用setSchedule函数时,它都会执行此操作,因为它会更新状态和父级,从而导致将更新的props传递给子级组件.

In the componentDidUpdate check for the previous date and time state values before calling the function otherwise it will be called whenever the date and time are defined and the component is updating which it will do whenever you call the setSchedule function as it updates the state and parent which inturn leads to updated props being passed down to the child component.

尝试

componentDidUpdate(prevProps, prevState) {
    const {setSchedule, channel} = this.props
    if(prevState.date !== this.state.data || prevState.time !== this.state.time) {
        if (this.state.date && this.state.time) {
           setSchedule(concatenateDateAndTime(this.state.date, this.state.time), channel)
        }
    }
  }

要确认父组件(子组件componentDidUpdate)中的任何更新,请查看此代码段

To confirm that any update in the parent component, the child components componentDidUpdate is called, have a look at this snippet

class Parent extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            clicked: false
        }
    }
    render() {
        return (
            <div>
                <Child />
                <button onClick={() => this.setState((prevState) => ({clicked: !prevState.clicked}))} > Toggle</button>
             </div>
        )
    } 
}

class Child extends React.Component {
   componentDidUpdate(prevProps, prevState) {
       console.log('update in child called');
   }
    render() {
        return (
            <div>
                Hello Child
             </div>
        )
    } 
}
ReactDOM.render(<Parent/>, document.getElementById('app'));

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>

这篇关于在无穷循环中进行代码锁定锁定-不涉及while循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆