【问题标题】:TypeError: Cannot read property 'publish' of undefined in (ReactJS)TypeError:无法读取(ReactJS)中未定义的属性“发布”
【发布时间】:2018-11-01 21:51:28
【问题描述】:

我的 main.js 文件中有这段代码:

import Link from 'gatsby-link';
import Cookies from 'universal-cookie';
import "isomorphic-fetch";
import React, { Component } from 'react';
import { render } from 'react-dom';
import './style.css';
import { MuiThemeProvider, createMuiTheme } from 'material-ui/styles';
import {amber,blue,red} from 'material-ui/colors';
import AppBar from 'material-ui/AppBar';
import Toolbar from 'material-ui/Toolbar';
import Typography from 'material-ui/Typography';
import Tabs, { Tab } from 'material-ui/Tabs';
import PropTypes from 'prop-types';
import { withStyles } from 'material-ui/styles';
import Table, { TableBody, TableCell, TableHead, TableRow } from 'material-ui/Table';
import Paper from 'material-ui/Paper';
import Button from 'material-ui/Button';
//import SingleInput from 'material-ui/components/SingleInput';  

import Avatar from 'material-ui/Avatar';
import DateRangeIcon from 'material-ui-icons/DateRange';
import AssignmentIcon from 'material-ui-icons/Assignment';
import NoteIcon from 'material-ui-icons/Note';
//import 'react-fab/dist/main.scss';
import * as firebase from 'firebase'

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',
      right: 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>
        <Paper id='calendar'>
          <Table>
            <TableHead>
              <TableRow>
                <TableCell><p id = "class1"></p></TableCell>
                <TableCell><p id = "class1info"></p></TableCell>
              </TableRow>
              <TableRow>
                <TableCell><p id = "class2"></p></TableCell>
                <TableCell><p id = "class2info"></p></TableCell>
              </TableRow>
              <TableRow>
                <TableCell><p id = "class3"></p></TableCell>
                <TableCell><p id = "class3info"></p></TableCell>
              </TableRow>
              <TableRow>
                <TableCell><p id = "class4"></p></TableCell>
                <TableCell><p id = "class4info"></p></TableCell>
              </TableRow>
              <TableRow>
                <TableCell><p id = "class5"></p></TableCell>
                <TableCell><p id = "class5info"></p></TableCell>
              </TableRow>
              <TableRow>
                <TableCell><p id = "class6"></p></TableCell>
                <TableCell><p id = "class6info"></p></TableCell>
              </TableRow>
              <TableRow>
                <TableCell><p id = "class7"></p></TableCell>
                <TableCell><p id = "class7info"></p></TableCell>
              </TableRow>
            </TableHead>
          </Table>
        </Paper>
      <form>

      <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 } 
      />
      </form>
      <Button variant="raised" color="secondary" style = {theme.bottomView} onClick={ this.publish }>
        Add
      </Button>
      </div>

    </MuiThemeProvider>



export default LoginPage

我有这个错误:

TypeError:无法读取未定义的属性“发布”

在这一行:

<Button variant="raised" color="secondary" style = {theme.bottomView}
onClick={ this.publish }>

我该如何解决这个问题?出了什么问题?有没有我遗漏的代码?

编辑:如果您需要更多代码或信息,请告诉我。

编辑/更多细节:我想点击一个按钮并运行发布功能。

【问题讨论】:

  • 最好更新完整代码。无法得到你想要做的事情
  • 好的一秒钟...
  • 我添加了完整的代码大家@aravind_reddy

标签: javascript reactjs react-native button properties


【解决方案1】:

首先,您的代码太难审核。

其次,你有一个try 没有catch

第三,函数或对象等类属性不需要用const 声明我认为这是你的主要问题。

编辑:我只是查看您重新发送的完整代码。 this.publish 是 Homework 类的类函数,LoginPage 在文件上下文中声明。所以 this.publish 意味着在你的模块中声明一个名为 publish 的函数。 -> 未定义

注意:要自动将函数与类绑定,只需使用箭头函数。

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

【讨论】:

  • 那么去掉const中的声明?
  • 澄清一下。你说删除'this.publish = this.publish.bind(this);'
  • 看看我编辑的答案,你第一次发送错误而不是完整的代码
  • ... 最后,我看到了 2 个函数发布,如果你想指向类中的函数,请使用 app.publish,如果你想指向外部函数,则只需调用发布。
  • 我在哪里使用 app.publish?我很新。
猜你喜欢
  • 2021-12-06
  • 2022-07-22
  • 2019-05-07
  • 2020-07-30
  • 1970-01-01
  • 1970-01-01
  • 2021-01-09
  • 1970-01-01
  • 2023-04-08
相关资源
最近更新 更多