React 尝试将道具分配给状态变量不起作用

React trying to assign props to state variable doesn't work

我正在尝试分配我从父组件获得的道具并将其分配给子组件中的状态(因为我想操作我首先分配给状态的道具数据)。

当我记录状态变量时,它作为一个空数组出现,但是当我在渲染中创建一个新变量并为其分配道具并记录它时。它确实显示了我需要的数据。另外,当我只记录 this.props 时,我肯定可以看到 props 包含我需要的数据。

我之前已经为 state 分配了几次 props,所以我不确定这次有什么不同以至于它不起作用。

我将道具传递给子组件的父组件:

  <ShowAvailableTimeslots onClick={this.getSelectedTimeslot} allTimeSlots={this.state.AvailabletimeSlots} /> 

我尝试将道具分配给状态的子组件:

class ShowAvailableTimeslots extends Component {
    constructor(props) {
      super(props)
        this.state = {
            sliceEnd: 5,
            sliceStart:0,
            selectedSlotValue: "",
            timeSlotArr: this.props.allTimeSlots,
            // timeSlotSlice: timeSlotArr.slice(this.state.sliceStart, this.state.sliceEnd)
        }
      
    }

    handleTimeSlotClick = (timeSlot) => {
        this.setState({ selectedSlotValue: timeSlot }, () => {
            this.props.onClick(this.state.selectedSlotValue)
            console.log('time slot value', timeSlot)
          
        });
    }
    previousSlots =()=>{
        var test;
    }
    forwordSlots =()=>{
        var test;
    }    

    
    render() {
         var timeSlotArrRender = this.props.allTimeSlots; 
        return (
            <React.Fragment>

                {console.log("state", this.state.timeSlotArr)} // --> doesn't show data
                {console.log("props", this.props)} // --> does show data
                {console.log("render variable", timeSlotArrRender )} // --> does show data


                <button className="button btn" onClick={() => this.previousSlots()} disabled={this.state.sliceStart === 0}>left</button>
                {/* {this.state.timeSlotArr.map(timeSlot => <a className="timeslot btn " key={timeSlot} value={timeSlot} onClick={() => this.handleTimeSlotClick(timeSlot)}>{timeSlot}</a>)
                } */}
                <button className="button btn">right</button>

            </React.Fragment>
        )
    }
}

export default ShowAvailableTimeslots

我觉得你不见了this.setState({})

我让它工作得很好。 https://jsfiddle.net/85zc4Lxb/

class App extends React.Component {
  render() {
    return (<Child passing="I am being passed to child" />);
  }
}

class Child extends React.Component {
  constructor(props) {
    super(props)
      this.state = {
        passedProp: this.props.passing,
      }
  }

  render() {
      return (
          <React.Fragment>
            <button>{this.state.passedProp}</button>
          </React.Fragment>
      )
  }
}

ReactDOM.render(
  <App />,
  document.getElementById('container')
);

我尝试重新创建场景并且成功尝试再次保存所有文件然后检查

parents分量

import React, { Component } from "react";
import TestOne from "./Components/TestOne/TestOne";

export class App extends Component {
  state = {
    x: "x data",
    y: "y data",
  };
  render() {
    return (
      <div>
        <TestOne x={this.state.x} allTimeSlots={this.state.y}/>
      </div>
    );
  }
}

export default App;

Child分量

import React, { Component } from "react";

export class TestOne extends Component {
  constructor(props) {
    super(props);
    this.state = {
      sliceEnd: 5,
      sliceStart: 0,
      selectedSlotValue: "",
      timeSlotArr: this.props.x,
    };
  }
  render() {
    var timeSlotArrRender = this.props.allTimeSlots;
    return (
      <React.Fragment>
        {console.log("state", this.state.timeSlotArr)}
        {console.log("props", this.props)}
        {console.log("render variable", timeSlotArrRender)}

        <button className="button btn">right</button>
      </React.Fragment>
    );
  }
}

export default TestOne;

结果:

构造函数在组件生命周期开始时被调用。 您正在从父级传递 this.state.AvailabletimeSlots ,到那时构造函数已经被调用并且 timeSlotArr 的分配已经完成,所以

timeSlotArr: this.props.allTimeSlots // will not work

你必须得到生命周期方法或钩子的帮助

componentWillReceiveProps(nextProps){
   this.setState({timeSlotArr: nextProps.allTimeSlots })
} 

根据新的变化你要使用

static getDerivedStateFromProps(nextProps, prevState){
   return {
      timeSlotArr: nextProps.allTimeSlots
  };
}