如何在构造函数中为函数赋值?

时间:2018-06-16 04:15:24

标签: reactjs

我需要通过React的上下文API访问一个函数,因为我在渲染位置方面有两个远程相关的组件,这些组件在数据交换中紧密相连。

最好的策略是使用React的上下文api(还没有使用redux)。我通常将函数作为props传递,但我需要通过上下文访问它们。我在上下文中定义了函数,我需要在构造函数中将它们分配给state。有没有办法做到这一点,或者我应该在componentDidMount中使用.setState?

现在在componentDidMount中设置状态正常,我不确定这是正确的方法。我的上下文提供程序类显示了我尝试在上下文状态中设置的函数。 这是我的上下文提供程序类:

import React from 'react';

const AppContext = React.createContext();



class AppProvider extends React.Component{
  state = {
    user: this.props.user,
    songs: [],
    nowPlaying: {},
    ended: false,
    paused: false,
    onPlaying: '',
    onEnd: '',
    onPausing: '',
    onSetSongs: ''
  }
  componentDidMount(){
    this.setState({
      user: this.props.user,
      onPlaying: this.handlePlaying,
      onEnd: this.handleEnd,
      onPausing: this.handlePausing,
      onSetSongs: this.handleSetSongs
    });
  }

  static getDerivedStateFromProps(props, state){
    return {user: props.user}
  }

  handleSetSongs = (songs) => {
    this.setState({songs});
  }

  handlePlaying = (song) => {
    this.setState({
      nowPlaying: song,
      ended: false,
      paused: false});
  }

  handlePausing = () => {
    if(this.state.paused){ this.handlePlaying(this.state.nowPlaying); }
    else{ this.setState({paused: true}) }
  }


  handleEnd = () => {
    var currentId = this.state.nowPlaying.idSongs;
    var index = this.state.songs.findIndex(function(song){ return song.idSongs === currentId; });
    var nextSong = this.state.songs[index+1];

    if(nextSong){ this.handlePlaying(nextSong); }
    else{ return }
  }

  render() {
    return (
      <AppContext.Provider value={this.state}>
        {this.props.children}
      </AppContext.Provider>
    )
  }
}

export {
  AppProvider,
  AppContext
};

2 个答案:

答案 0 :(得分:2)

您无需将功能设置为状态,因为它们很可能不会被更改。您可以像

一样简单地传递它们
this.update()

答案 1 :(得分:0)

你可以做这样的事情来利用上下文:

const ThemeContext = React.createContext('light')
class ThemeProvider extends React.Component {
  state = {theme: 'light'}
  render() {
    return (
      <ThemeContext.Provider value={this.state.theme}>
        {this.props.children}
      </ThemeContext.Provider>
    )
  }
}
class App extends React.Component {
  render() {
    return (
      <ThemeProvider>
        <ThemeContext.Consumer>
          {val => <div>{val}</div>}
        </ThemeContext.Consumer>
      </ThemeProvider>
    )
  }
}

了解有关使用上下文https://medium.com/dailyjs/reacts-%EF%B8%8F-new-context-api-70c9fe01596b

的详情