reactjs react setstate在将元素推到数组时不工作

yzxexxkh  于 2023-05-22  发布在  React
关注(0)|答案(3)|浏览(133)

我试图将元素推送到组件状态中的对象数组中(在react.js中),我调用方法Array.concat,它返回一个新数组。

pushDeck(id, name) {
  var newDeck = [{
    id: id,
    name: name
  }];
  console.log("new path should be: ", this.state.path.concat(newDeck));
  this.setState({
    path: this.state.path.concat(newDeck)
  }, () => {
    console.log("setstate callback: ", this.state.path);
  });
}

第一个console.log打印路径数组的正确值,但在调用setstate的回调函数后,第二个console.log打印一个空数组。就像这样。setState什么也没做
更多详情:我从一个grandChild组件调用pushDeck,我给予pushDeck函数作为组件DeckGallery的一个prop,这个组件把这个函数给它的一个子组件。以下是整个主要组件:

import React, {Component} from "react";
import Page from "../components/page.jsx";
import Radium from "radium";
import {connect} from "react-redux";
import {getUserInfo} from "../actions/user";
import {successAlert} from "../actions/alerts";
import {fetchUserDecks, deleteUserDeck} from "../actions/deck.js";
import RaisedButton from 'material-ui/RaisedButton';
import CreateUserDeckContainer from "../containers/createUserDeckContainer.jsx";
import DeckGallery from "../components/deckGallery.jsx";
import _ from "lodash";

const style = {
    row1:{
        margin: "5px"
    },
    path:{
        color: "blue",
        cursor: "pointer"
    }
}

class Home extends Component{

    constructor(props){
        console.log("home constructor");
        super(props);
        this.state = {parentId:null, path:[]};
        this.fetchDecks = this.fetchDecks.bind(this);
        this.renderPath = this.renderPath.bind(this);
        this.goToIndex = this.goToIndex.bind(this);
        this.onDelete = this.onDelete.bind(this);
        this.pushDeck = this.pushDeck.bind(this);
    }

    componentWillMount(){
        console.log("will mount");
        this.props.getUserInfo();
    }

    fetchDecks(skip){
        console.log("fetch decks");
        this.props.fetchUserDecks(this.state.parentId, skip, this.state.path);
    }

    goToIndex(pathLastIndex){
        console.log("goto index", this.state.path);
        var limitToDrop = this.state.path.length - pathLastIndex;
        var newPath = _.dropRight(this.state.path, limitToDrop);
        this.setState({path: newPath});
    }

    pushDeck(id, name){
        var newDeck = [{id: id, name: name}];
        console.log("new path should be: ", Array.from(new Set(this.state.path.concat(newDeck))));
        this.setState({path: Array.from(new Set(this.state.path.concat(newDeck)))},
            ()=>{
            console.log("setstate callback: ", this.state.path);
        });
    }

    componentWillUpdate(nextProps, nextState){
        console.log("nextstate: ",  nextState);
    }

    renderPath(){
        return (
            <div>
                <span onClick={()=>this.goToIndex(0)} style={style.path}>Root</span>
                {this.state.path.map((p, i)=>{
                    <span key={(i+1)} onClick={()=>this.goToIndex(i+1)} style={style.path}>{p.name}</span>
                    })
                }
            </div>
        );
    }

    onDelete(deckId){
        console.log("on delete");
        this.props.deleteUserDeck(deckId, this.state.path, ()=>{
            this.props.successAlert("Deck deleted succesfully !");
            this.forceUpdate();
        });
    }

    render(){
        console.log("path at render: ", this.state.path);
        return (
            <Page name="my collection">
                <div className="container">
                    <div style={style.row1} className="row">
                        <div className="col-lg-9  col-sm-6">
                            <h2>Your decks</h2>
                             Path: {this.renderPath()}
                        </div>
                        <div className="col-lg-3 col-sm-6">
                            <CreateUserDeckContainer path={this.state.path}/>
                        </div>
                    </div>
                    <div className="row">
                        <div className="col">
                            <DeckGallery pushDeck={this.pushDeck} onDelete={this.onDelete} path={this.state.path} fetch={this.fetchDecks} decks={this.props.decks}/>
                        </div>
                    </div>
                </div>
            </Page>
        );
    }
}

function mapStateToProps(state){
    return {decks: state.userDecks};
}

export default connect(mapStateToProps, {getUserInfo, fetchUserDecks, deleteUserDeck, successAlert})(Radium(Home));

**更新:**我将错误隔离为:

goToIndex(that){
        console.log("path at gotoindex: "+ JSON.stringify(that.state.path));
    }

    renderPath(){
        var that = this;
        console.log("path at renderpath: "+ JSON.stringify(that.state.path));   
        setTimeout(()=>{
            that.goToIndex(that);
        }, 0);
        that.goToIndex(that);
    }

当我调用render时,这是在控制台中打印的内容:

path at renderpath: [{"id":"59cec39e3724bc137d935ed5","name":"math"}]
path at gotoindex: [{"id":"59cec39e3724bc137d935ed5","name":"math"}]
path at gotoindex: []

当在setTimeout内部调用goToIndex时打印最后一行,它应该打印与在setTimeout外部调用时相同的内容。另外,我在componentWillUpdate中放置了一个console.log,以查看在两次调用的过程中状态是否发生了变化,但没有发生。

zaqlnxep

zaqlnxep1#

this不绑定到您在回调中的想法。
使用箭头语法声明函数可能会解决这个问题。
看看这个答案,我想可能会有帮助。

qacovj5a

qacovj5a2#

问题是我传递了一个数组给孩子们,因为在Javascript中数组是通过引用传递的,孩子们正在修改数组!,即:子节点在没有父节点监督的情况下修改父节点的状态:p。解决方案是在将数组传递给子数组之前克隆它,为此,我使用了Array类中的方法slice()

eoigrqb6

eoigrqb63#

试试这个:

pushDeck(id, name) {
  .....
  .....
  this.setState({
      path: [...new Set([...this.state.path, ...newDeck])],
      () => console.log("setstate callback: ", this.state.path);
   });
 ......
}

相关问题