开发者问题收集

尝试在点击时更新状态

2021-07-26
182

因此,当用户单击按钮时,我尝试将以下内容更新为 true 或 false。

但是它不起作用,一直抛出

TypeError: _this.setState is not a function. (In '_this.setState(function (state) {
        return {
          icon: !state.icon
        };
      })', '_this.setState' is an instance of Object)

我的操作代码是

 handleClick = (e) => {
        console.log(e)
        
        this.setState((state) => {
          return { icon: !state.icon };
        });
    }

它旨在与

export default class Mediaplayer extends React.Component{

  constructor(props) {
        super(props);
        this.state = {
            error: null,
            isLoaded: false,
            items: [],
            station:null,
            icon: false,
         };
    }

完整代码

import React, {useState} from 'react'
import { v4 as uuidv4 } from 'uuid';
import Image from 'next/image';
import { Container, Card, Row, Col, DropdownButton, Dropdown, ProgressBar } from 'react-bootstrap'
import { PlayCircle, PauseCircle } from 'react-bootstrap-icons';



export default class Mediaplayer extends React.Component{
    constructor(props) {
        super(props);
        this.handleClick = this.handleClick.bind(this);
        this.state = {
            error: null,
            isLoaded: false,
            items: [],
            station:null,
            icon: false,
         };
    }
   
     

    
    componentDidMount() {
        const token = uuidv4();
        // alert("hello");
        if(!sessionStorage['uuid']){
            sessionStorage.setItem("uuid",token);
        }
        console.log(token);
        if(!sessionStorage['station']){
            sessionStorage.setItem("station","DRN1");
        }
      
        if(!sessionStorage['live']){
            sessionStorage.setItem("live",true);
        }

        this.setState = {
            station: "https://example.com/station/DRN1?uuid="+sessionStorage['uuid']
        }

        document.getElementById("player").src= "https://example.com/station/"+sessionStorage['station']+"?uuid="+sessionStorage['uuid'];
        document.getElementById("player").muted = true;
        document.getElementById("player").play();

      setInterval(() => {
        this.nowplaying();
      }, 30000);
    
      this.mediamute();
    }

    mediamute(){
        var myAudio = document.getElementById('player');
        document.getElementById('player').dispatchEvent(new MouseEvent("click",{bubbles: true, cancellable: true}));
        document.getElementById('player').click();
        if (myAudio.duration) {
            console.log("playing")
            setTimeout(function(){
            
            document.getElementById("player").muted = false;
            document.getElementById("player").play();
            }
            , 10000)
         }
         else{
             console.log("NOT PLAYING")
             setTimeout(this.mediamute,2000);
         }
    }


    nowplaying(){
       console.log("running now playing info")
         fetch("https://example.com:9000/nowplaying/"+sessionStorage.station+"?uuid="+sessionStorage['uuid'])
         
         .then(res => res.json())
         .then((result) => {
             console.log(result)
             document.getElementById("Now_Playing_Artist").innerHTML = result.data[0].track.artist;
             document.getElementById("Now_Playing_Title").innerHTML = result.data[0].track.title;
             //document.getElementById("Now_Playing_Cover").src = result.data[0].track.imageurl;
             document.getElementById("Now_Playing_Cover").srcset = result.data[0].track.imageurl;
         
         }
         )
  
    }
    
  
    handleClick(){
       /* this.setState(prevState => ({
          icon: !prevState.icon
        }));*/
        this.setState({ //the error happens here
            icon: true
        });
    };
    


    render(){
        const { station, icon } = this.state;
      
       //  var streamurl = icyStream;//window.com_adswizz_synchro_decorateUrl(icyStream); 
            console.log(station);
            return  <div className="mediaplayerbg">
                            <Container fluid="sm">
                                <Row className="justify-content-md-center">
                                    <Col lg={1} xs={2}>
                                        <Image id="Now_Playing_Cover" src="https://storage.googleapis.com/radiomedia-images/station_logos/DRN1Logo.png" width="60" height="60"/>
                                    </Col>
                                    <Col lg={3} xs={7}>
                                        <Row id="Now_Playing_Artist">ARTIST</Row>
                                        <Row id="Now_Playing_Title">SONG</Row>
                                    </Col>
                                    <Col lg={1} xs={2} id="mediaControl" >
                                     <i className='large material-icons' onClick={this.handleClick}>
                                            { icon ? 'play_circle_outline' : 'pause_circle_outline'}</i>
                                    </Col>
                                  
                                </Row>
                            </Container>
                                                 
                            <audio id="player" src={station}  controls={true} hidden={true}/>
                    </div>
    }

}

请注意,这只是 nextjs 应用程序内的一个组件。 我想知道这是否更像是 nextjs 问题,因为它似乎只发生在 nextjs 应用程序中。

2个回答
  1. 首先,当您使用箭头函数时,您会获得当前值,因此当您设置状态并将其设置为状态中的当前值时,什么也不会发生。
this.setState(state => ({
              cart: [...state.cart, product.name],
              total: state.total + product.price
            }))

这是使用箭头函数更新的方式

  1. 我不知道您的组件中有什么,但我建议您使用函数组件,因为处理状态更改要容易得多
const [state,setState] = useState(0);
    setState(3)
TalOrlanczyk
2021-07-26

你需要在组件构造函数中绑定 this.handleClick

this.handleClick = this.handleClick.bind(this);

然后你可以像这样使用它:

handleClick() {
    this.setState(prevState => ({
     //do something wih prevState
    }));
  }
Nemanja
2021-07-26