相关疑难解决方法(0)

React ES6父子组件状态问题

我是新手,想要根据react-starter-kit构建一个简单的ToDo应用程序.我正在使用ES6类,无法找到从子组件更新父状态的方法.

这是代码:

import React, { PropTypes, Component } from 'react';
import withStyles from '../../decorators/withStyles';
import styles from './ToDoPage.less';


@withStyles(styles)
class ToDoPage extends Component {

  static contextTypes = {
    onSetTitle: PropTypes.func.isRequired
  };

  constructor() {
    super();
    this.state = {
      items: ['Item1', 'Item2'],
      value: ''
    };
  }

  updateValue(newValue) {
    //this.state is null here
    this.setState({
      value: newValue 
    });
  }

  clickHandler() {
    console.log('AddToDo state:', this.state)
    if (this.state.value && this.state.items) { //this.state is null here
      this.setState({
        items: this.state.items.push(this.state.value)
      });
    }
  }

  render() {
    let title = …
Run Code Online (Sandbox Code Playgroud)

javascript reactjs

5
推荐指数
2
解决办法
4773
查看次数

如何从回调函数访问状态

我在 react native 中有一个组件:

export default class Screen extends Component {
  constructor(props){
    super(props);
    this.state = {
      prop1: false,
      prop2: simpleFunc
    };
  }
  simpleFunc = () => { /*...*/ }

  componentWillMount() {
      BackgroundGeolocation.on('location', this.onLocation);
Run Code Online (Sandbox Code Playgroud)

最后一行是将在新位置调用的回调方法。
从该方法我无法访问this.state或this.simpleFunc().

我应该怎么做才能从回调函数更新状态?

javascript ecmascript-6 reactjs react-native

5
推荐指数
1
解决办法
4111
查看次数

ES6 /用"ajax"反应"this"关键字以从服务器获取数据(教程)

我正在关注React Beginner Tutorial,我正在尝试将其翻译成ES6.然而,当我改变了CommentBox一个ES6类它开始给我一个this.props.url是undefined错误(在AJAX调用loadCommentsFromServer).我认为这与ES6如何绑定有关this,但是我对语言(也不是React)不太熟悉,所以我不确定.我查看了React 0.13发行说明并看到了这个:

React.createClass具有内置的魔术功能,可以this自动为您绑定所有方法.对于那些在其他类中不习惯此功能的JavaScript开发人员来说,这可能会有点混乱,或者当他们从React迁移到其他类时会让人感到困惑.

我不完全确定,但我认为这意味着我必须保存它的价值(如在let that = this和中.bind(that)),但同样this.props.url也是undefined- 我不知道下一步该去哪里.

这是我目前的代码:

class CommentBox extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: []
    };
  }
  loadCommentsFromServer() {
    $.ajax({
      url: this.props.url,
      dataType: 'json',
      cache: false,
      success: function(data) {
        this.setState({
          data: data
        })
      }.bind(this)
    });
  }
  handleCommentSubmit(comment) {
    var comments = this.state.data;
    var newComments = comments.concat([comment]);
    this.setState({ …
Run Code Online (Sandbox Code Playgroud)

javascript class this ecmascript-6 reactjs

4
推荐指数
1
解决办法
3426
查看次数

未捕获的TypeError:无法读取null的属性"setState"

我刚接触使用react并遇到了问题:

未捕获的TypeError:无法读取null的属性"setState".

基本上我要做的是,用户可以点击三个不同的标题,点击后,它将呈现特定于该标题的特定模板.这是我正在使用的代码,它给了我这个错误:

class Selection extends React.Component {

constructor(props) {
    super(props);
    this.state = {selections: [], donateActive: true, fundraiseActive: false, speakActive: false };
}

componentDidMount() {
    this.setState({
        selections: selectionData.selections
    })
}

componentWillUnMount(){
    console.log("unmounted!"); 
}

donateOnClick() {
    this.setState({ donateActive: true, fundraiseActive: false, speakActive: false});
}

fundraiseOnClick() {
    this.setState({ fundraiseActive: true, donateActive: false, speakActive: false});
}

speakOnClick() {
    this.setState({ speakActive: true, fundraiseActive: false, donateActive: false});
}

donateTemplate() {
    return (
        <div>
            <h1>donate template</h1>
        </div>
    )
}   

fundraiseTemplate() {
    return (
        <div>
            <h1>fundraise template</h1> …
Run Code Online (Sandbox Code Playgroud)

reactjs

4
推荐指数
1
解决办法
4924
查看次数

反应 - 无法读取未定义的属性

通常,当我单击子组件中的菜单项时,它会调用 {this.handlesort},这是一个本地函数。处理排序从我的父组件接收 onReorder 道具。{onReorder} 调用名为 reOrder 的本地函数。它设置 {orderBy 和 orderDir} 的状态。问题是,当我单击 {menuitem} 时,它立即返回此错误。(未捕获的类型错误:无法读取未定义的属性“onReOrder”)。通常它在我不使用 es6 时工作。请帮忙

(父组件)

export default class TenantView extends Component {
    constructor(props) {
        super(props);
        //setting state
        this.state = {
            //tenants: [],
            orderBy: 'name',
            orderDir: 'asc',};
    };
    componentWillMount() {
        this.setState({
            tenants:[{img: 'tenant1.jpg',name: 'John', address: '7 Gilbert', 
                     paid: 'true'},{img: 'tenant2.jpg',name:'Abba', address: 
                     '3 Vecq st', }]});//setState
    }//componentWillMount



    reOrder(orderBy, orderDir) {
        this.setState({
            orderBy: orderBy,
            orderDir: orderDir,
        });//setState
    }//reorder

    render(){
        var tenants = this.state.tenants;
        var orderBy = this.state.orderBy;
        var orderDir = this.state.orderDir;

        tenants …
Run Code Online (Sandbox Code Playgroud)

meteor ecmascript-6 reactjs

4
推荐指数
1
解决办法
2万
查看次数

Reactjs this.setState不是函数错误

我是新手React js,我不知道下面的代码有什么问题,但我得到的setState不是函数错误.请帮我解决这个问题.

class AppBarLayout extends React.Component {
  constructor(props) {
      super(props);

      this.state = {
        visibleSideBar:true,
        slide:""
      }
  }
  showProfile(){

    this.setState({
        slide:'slide'
    });
    console.log(this.state.slide);
  }
  render(){
    return(
            <div>
        <header>
          <NavBar show={this.showProfile}/>
          <Profile slide={this.state.slide} />
        </header>
      </div>
    );
  }
}
export default AppBarLayout;
Run Code Online (Sandbox Code Playgroud)

reactjs

3
推荐指数
2
解决办法
8798
查看次数

在es6类中反应'这个'上下文

使用ReactJS的es6方法与类中的方法中的'this'关键字的上下文混淆

这给出了一个错误,无法获得未定义的引用

class AddItem extends React.Component {
    constructor() {
        super();
    }
    addIt(e) {
        e.preventDefault();
        let newItem = {
            title: this.refs.title.value
        }
        this.refs.feedForm.reset();
        this.props.addItem(newItem);
    }
    render() {
        return (
            <div>
              <form ref="feedForm" onSubmit={this.addIt}>
                <div className="input-group">
                  <span className="input-group-addon"><strong>Title:</strong></span>
                  <input ref="title" type="text" className="form-control" />
                </div>
                <button className="btn btn-success btn-block">Add Item</button>
              </form>
            </div>
        );
    }
}
Run Code Online (Sandbox Code Playgroud)

但这似乎工作正常

class AddItem extends React.Component {
    constructor() {
        super();
        this.addIt = function(e) {
            e.preventDefault();

            let newItem = {
                title: this.refs.title.value
            }

            this.refs.feedForm.reset();
            this.props.addItem(newItem);
        }.bind(this)
    }

    render() {
        return …
Run Code Online (Sandbox Code Playgroud)

javascript ecmascript-6 reactjs

2
推荐指数
1
解决办法
332
查看次数

this.state在reactjs组件中为null

我只是尝试一些简单的东西,比如只在handleSubmit函数中打印this.state.validForm,但我似乎无法访问this.state.validForm.首先我直接尝试使用此功能,但无济于事.我是新来的反应.

import React, { Component } from 'react';
import TextInput from './TextInput';

class RequestForm extends Component {
    constructor(props) {
        super(props);
        this.state = {validForm : "false"};
        this.getInfoForm = this.getInfoForm.bind(this);
    }

    getInfoForm() {
        return this.state.validForm;
    }

    handleSubmit(event) {
        event.preventDefault();
        console.log('submit values are');
        console.log(event.target.src.value);
        console.log(event.target.email.value);
        console.log(this.state.validForm);
        console.log(this.getInfoForm());
    }

    render() {
        return (
            <form onSubmit={this.handleSubmit}>
                <TextInput
                    uniqueName="email"
                    name="email"      
                    text="Email Address"
                    required={true}     
                    minCharacters={6}
                    validate="email" 
                    errorMessage="Email is invalid"
                    emptyMessage="Email is required"
                />

                <TextInput 
                    text="User"
                    name="User src"
                    required={true}
                    minCharacters={3}
                    validate="notEmpty"
                    errorMessage="Name is invalid"
                    emptyMessage="Name is required"
                /> …
Run Code Online (Sandbox Code Playgroud)

reactjs react-jsx

0
推荐指数
1
解决办法
2191
查看次数

React:在ES6类中访问上下文

使用ES6类语法,我无法保留context类中其他方法的值.例如:

class Repos extends React.Component {
  constructor(props, context) { // eslint-disable-line
    super(props, context);
    console.log(this.context.router);
  }

  handleSubmit(event) {
    event.preventDefault();
    const userName = event.target.elements[0].value;
    const repo = event.target.elements[1].value;
    const path = `/repos/${userName}/${repo}`;
    console.log(path); // eslint-disable-line
    this.context.router.push(path);
  }
Run Code Online (Sandbox Code Playgroud)

对于第一个控制台日志,上下文仍然存在:

在此输入图像描述

对于第二个控制台日志,不是那么多:

在此输入图像描述

如何this.context在构造函数之外的方法中处理,但在类中?

javascript ecmascript-6 reactjs

0
推荐指数
1
解决办法
1687
查看次数

这在React类函数中为null

我重构了一个从ES5到ES6的React类,现在当我点击一个调用按钮时,行开头this.state.dispatch(logIn(this.state.logIn))的初始this值为null.超级怪异.

这是我的班级:

class Home extends Component {
    constructor(props) {
        super(props);

        this.state = {
            panelIsOpen: false,
            registration: {},
            login: {},
        };
    }

    signUp() {
        this.props.dispatch(signUp(this.state.registration));

        this.setState({
            registration: {},
        });
    }

    logIn() {
        debugger; // this is `null here`
        this.props.dispatch(logIn(this.state.login));

        this.setState({
            login: {},
        });
    }

    togglePanel(e) {
        this.setState({ panelIsOpen: !this.state.panelIsOpen} );
    }

    render() {
        const {elements} = this.props;
        const {registration, login} = this.state;

        return (
            // some stuff 
        );
    }
};

Home.propTypes = {
    elements: React.PropTypes.array,
    dispatch: React.PropTypes.func, …
Run Code Online (Sandbox Code Playgroud)

javascript ecmascript-6 reactjs react-redux

0
推荐指数
1
解决办法
2069
查看次数

无法读取 ReactJS 中未定义的属性“状态”(Gatsby)

我有以下代码:

export default class Contact extends React.Component {
    constructor(props) {
      super(props);
      this.state = {
        password: '',
        redirect: false,
        username: ''
      };

  this.onUsernameChange = this.onUsernameChange.bind(this);
  this.onPasswordChange = this.onPasswordChange.bind(this);
}

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

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

handleSubmit(event) { 
  event.preventDefault();
  alert('A name was submitted: ' + this.state.username);

  //sessionStorage.setItem('username', this.state.username);

}

render() {

  return (
      <div>
        <form className="form-signin" onSubmit={this.handleSubmit}>
          <input type="text" value={this.username} onChange={this.onUsernameChange} />
          <input type="password" value={this.password} onChange={this.onPasswordChange} />
          <input type="submit" value="Submit" />
        </form>
      </div>
  ); …
Run Code Online (Sandbox Code Playgroud)

javascript event-handling reactjs gatsby

0
推荐指数
2
解决办法
2万
查看次数