【问题标题】:TypeError: this.setState is not a functionTypeError:this.setState 不是函数
【发布时间】:2018-05-23 05:01:28
【问题描述】:

这是我的代码:

const cookies = new Cookies();
var name = (cookies.get('name'));
var key = (cookies.get('key'));
console.log(key);
const theme = createMuiTheme({
  palette: {
    primary: amber,
    secondary: blue
  },
  root: {
    flexGrow: 1,
  },
  bottomView: {

    width: '25%',
    height: 50,
    backgroundColor: '#FF9800',
    justifyContent: 'center',
    alignItems: 'center',
    position: 'absolute',
    bottom: 0
  },
});
class Base {
  constructor() {}
}

class Homework extends Base {
  constructor() {
    super();

    this.state = {
      topicBox: null,
      payloadBox: null
    };

    this.publish = this.publish.bind(this);
    this.handleChange = this.handleChange.bind(this);
  }
 publish(event) {
    this.setState({value: event.target.value});
  }
  handleChange(event) {
    this.setState({value: event.target.value});
  } 


  async loadTest() {
    try {
      //grab courses
      const response = await fetch('https://classroom.googleapis.com/v1/courses?access_token=' + key);
      const json = await response.json();
      //coursemax vars will eventually be user defined
      var coursemax = [2, 2, 2, 2, 2, 2, 2, 2];

      if (json.courses != null) {
        for (var course = 0; course < json.courses.length && course < 9; course++) {
          //grab course info
          var coursework = await fetch('https://classroom.googleapis.com/v1/courses/' + json.courses[course].id + '/courseWork?access_token=' + key);
          var coursejson = await coursework.json();
          console.log(coursejson);
          var assignment = "";
          for (var assignmentnum in coursejson.courseWork) {
            if (assignmentnum <= coursemax[course] - 1) {
              //add in assignment
              assignment += "<p>" + coursejson.courseWork[assignmentnum].title + "</p>";
              //"Due: "+coursejson.courseWork[assignmentnum].dueDate.month+"/"+coursejson.courseWork[assignmentnum].dueDate.day
            }
          }
          //making ids to render
          document.getElementById('class' + (course + 1) + 'info').innerHTML = assignment;
          document.getElementById('class' + (course + 1)).innerHTML = json.courses[course].name + '</b>' + ':' + '<br/>';;
        }
      }
    } catch (err) {
      console.log(err);
    }
  }
}
var app = new Homework();
var config = {
  apiKey: "xxx",
  authDomain: "xxx",
  databaseURL: "xxx",
  projectId: "xxx",
  storageBucket: "xxx",
  messagingSenderId: "xxx"
};
firebase.initializeApp(config);
app.loadTest();

function publish() {
  console.log(this.state.topicBox, this.state.payloadBox);
  const itemsRef = firebase.database().ref('Users');
  const item = {
    title: this.state.topicBox,
    user: this.state.payloadBox
  }
  itemsRef.push(item).set("name");
  this.setState({
    topicBox: '',
    payloadBox: ''
  });

}

const LoginPage = () =>
<MuiThemeProvider theme={theme}>
      <div>
        <AppBar position="static" id='title'>
          <Toolbar>
            <Typography type="title" color='inherit'>
              MVHS Homework App
            </Typography>
            <div id='avatar' color='inherit'><Avatar>{name[0]}</Avatar></div>
          </Toolbar>
        </AppBar>

      <input 
        type="text" 
        name="topicBox" 
        placeholder="Name" 
        value={ this.state.topicBox }
        onChange={ this.handleChange } 
      />
      <input 
        type="text" 
        name="payloadBox" 
        placeholder="Details"
        value={ this.state.payloadBox } 
        onChange={ this.handleChange } 
      />
      <Button variant="raised" color="secondary" style = {theme.bottomView} onClick={ this.publish }>
        Secondary
      </Button>
      </div>

    </MuiThemeProvider>



export default LoginPage

在上面的代码中,有一个错误:

this.setState({value: event.target.value});

错误是:

TypeError: this.setState 不是函数

为什么会这样?

编辑: 我认为该错误是目前代码的唯一问题。如果还有更多错误,请随时告诉我。 :)(我是不是也没有正确设置汽车?)

编辑:此代码是否会将已编辑文本输入的值发送到数据库?

【问题讨论】:

  • 错误是因为function publish 无权访问this,因此无法访问setState。那应该在反应类中。
  • 扩展Component,不是基类,是的,你有更大的问题
  • 还有什么问题?
  • 此代码是否会将一个带有已编辑文本输入的值发送到数据库? @BoyWithSilverWings
  • 我不明白你在做什么?您不需要调用诸如正确使用状态提升props 之类的函数。学习新的 ES6 箭头函数和词法this

标签: javascript reactjs react-native constants setstate


【解决方案1】:

您需要使用组件扩展您的作业。而且您还尝试使用称为“值”的未知键设置状态

import React,{ Component } from 'react';
class Homework extends Component {
  constructor(props) {
    super(props);

    this.state = {
      topicBox: null,
      payloadBox: null
    };

    this.publish = this.publish.bind(this);
    this.handleChange = this.handleChange.bind(this);
  }
  publish(e) {
    const { name, value } = e.target;
    this.setState({ [name]: value});  // this will set your state of current input, that you were handling
    //this.setState({value: event.target.value});
  }
  handleChange(e) {
    const { name, value } = e.target;
    this.setState({ [name]: value}) 
    //this.setState({value: event.target.value});
  }

   render(){
     return(
       // your code
       <div>
         <LoginPage handleChange={this.state.handleChange} publish={this.state.publish} topicBox={this.state.topicBox} payloadBox={this.state.payloadBox}  />
       </div>
     )
   } 
}

这是您的功能组件,因为您正在尝试更改您的状态。您不能直接从功能组件内部的此处更改状态。实际上,您可以将函数(handleChange 和 publish)作为道具传递给功能组件(LoginPage)。您可以使用以下链接作为参考https://hackernoon.com/react-stateless-functional-components-nine-wins-you-might-have-overlooked-997b0d933dbc

https://code.tutsplus.com/tutorials/stateful-vs-stateless-functional-components-in-react--cms-29541

// here you can access the function as props. ie the Homework component passed its state such as topicBox, payloadBox, handleChange function and publish function as a props to LoginPage functional component. Here you can access it by using  props.handleChange (which is the prop name mentioned in Homework component)

export const LoginPage = (props) =>
<MuiThemeProvider theme={theme}>
      <div>
        <AppBar position="static" id='title'>
          <Toolbar>
            <Typography type="title" color='inherit'>
              MVHS Homework App
            </Typography>
            <div id='avatar' color='inherit'><Avatar>{name[0]}</Avatar></div>
          </Toolbar>
        </AppBar>

      <input 
        type="text" 
        name="topicBox" 
        placeholder="Name" 
        value={ props.topicBox }
        onChange={ props.handleChange } 
      />
      <input 
        type="text" 
        name="payloadBox" 
        placeholder="Details"
        value={ props.payloadBox } 
        onChange={ props.handleChange } 
      />
      <Button variant="raised" color="secondary" style = {theme.bottomView} onClick={props.publish }>
        Secondary
      </Button>
      </div>

    </MuiThemeProvider>

【讨论】:

  • 当我更改文本框时,我收到未定义 e 的错误。 @Jeeva
  • 更新文本时出现此错误。 Warning: setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op. Please check the code for the component.
  • @Jim Hall,你不能为作为你的功能组件的无状态组件设置状态,实际上你可以为它传递道具
  • 我已经更新了答案,你可以像上面那样尝试
  • 我收到此错误:TypeError: Cannot read property 'state' of undefined 在此行:value={ this.state.topicBox } @Jeeva
猜你喜欢
  • 2017-09-11
  • 1970-01-01
  • 2023-04-09
  • 2020-12-15
  • 1970-01-01
  • 1970-01-01
  • 2017-05-06
  • 2019-12-20
相关资源
最近更新 更多