class Main extends Component{
constructor(props){
super(props);
this.state = {
loggedIn:false,
//This is where the user currently is
pagenum : 0,
//This is all the steps the user will take
steps : [{name:'Menu', type:"menu", active:true, completed:false, stepnumber:0},
{name:'Step 1', type:"idea01",active:false, completed:false, stepnumber:1},
{name:'Step 2', type:"idea02",active:false, completed:false, stepnumber:2},
{name:'Step 3', type:"idea03",active:false, completed:false, stepnumber:3}]
};
}
moveAlong(to, fro){
let newArray = [...this.state.steps];
//updating the step within the new array with the new active variable
newArray[this.state.pagenum] = {...newArray[this.state.pagenum], active: !newArray[this.state.pagenum].active}
newArray[fro] = {...newArray[this.state.pagenum], completed: !newArray[this.state.pagenum].completed}
console.log(...newArray);
//replacing the previous array with new array with new info
this.setState({ steps: newArray});
}
render(){
return[
<Sidebar steps={this.state.steps} pageNum={this.state.pagenum}/>
...
];
}
}
一旦从子组件调用moveAlong,处于我状态的数组就会更新。但是,传递到Sidebar组件的数组不会在Sidebar函数中更新。有什么想法吗?
TLDR:moveAlong()得到执行,但对数组的更改未反映到补充工具栏的下游
编辑:在下面添加了侧边栏代码:
import React, {Component} from 'react';
import Step from './Step';
import '../styles/style.css';
class Sidebar extends Component {
//bringing in the array of "steps" from the parent Main
constructor(props) {
super(props);
this.state = {
//storing the array in local state
pagenum: props.pageNum,
stepsnodes: props.steps
};
}
render() {
//shifting the array into a list to be rendered passsing through the step's specifics
const listItems = this.state.stepsnodes.map((d) => <Step active={d.active} name={d.name} completed={d.completed} stepnumber={d.stepnumber}/>);
console.log("Sidebar's arraystatus: " + listItems);
return(
<div className ="sidebar">
{listItems}
</div>
);
}
}
export default Sidebar;
´´´
问题似乎是步骤已在其构造函数中加载到Sidebar
的状态-因此在安装时仅加载一次:
constructor(props) {
super(props);
this.state = {
//storing the array in local state
pagenum: props.pageNum,
stepsnodes: props.steps
};
}
如果将render方法更改为使用props而不是state,那么它应该起作用
const listItems = this.state.stepsnodes.map(..)
// to
const listItems = this.props.stepsnodes.map(..)