我想在state数组的末尾添加一个元素,这是正确的方法吗?
this.state.arrayvar.push(newelement);
this.setState({arrayvar:this.state.arrayvar});
我担心,就地修改阵列push可能会引起麻烦-是否安全?
制作数组副本的另一种选择setState似乎是浪费的。
我想在state数组的末尾添加一个元素,这是正确的方法吗?
this.state.arrayvar.push(newelement);
this.setState({arrayvar:this.state.arrayvar});
我担心,就地修改阵列push可能会引起麻烦-是否安全?
制作数组副本的另一种选择setState似乎是浪费的。
Answers:
该阵营的文档说:
将this.state视为不可变的。
您push将直接更改状态,即使您此后再次“重置”状态,也有可能导致易于出错的代码。F.ex,它可能导致某些生命周期方法(如componentDidUpdate不会触发)。
在更高版本的React中,建议的方法是在修改状态以防止竞争情况时使用updater函数:
this.setState(prevState => ({
  arrayvar: [...prevState.arrayvar, newelement]
}))
与使用非标准状态修改可能会遇到的错误相比,内存“浪费”不是问题。
早期React版本的替代语法
您可以使用concat干净的语法,因为它会返回一个新数组:
this.setState({ 
  arrayvar: this.state.arrayvar.concat([newelement])
})
在ES6中,您可以使用Spread运算符:
this.setState({
  arrayvar: [...this.state.arrayvar, newelement]
})
              push返回新的数组长度,因此它将不起作用。同样,setStateasync和React可以将多个状态更改排队到一个渲染通道中。
                    setState两次,它显示了两个类似的设置状态数组的示例,但不直接对其进行更改。
                    let list = Array.from(this.state.list); list.push('woo'); this.setState({list});当然,修改您的样式首选项。
                    如果使用,最简单ES6。
initialArray = [1, 2, 3];
newArray = [ ...initialArray, 4 ]; // --> [1,2,3,4]
新数组将是 [1,2,3,4] 
在React中更新您的状态
this.setState({
         arrayvar:[...this.state.arrayvar, newelement]
       });
              最简单的方法是ES6:
this.setState(prevState => ({
    array: [...prevState.array, newElement]
}))
              tableData = [['test','test']]后推我的新数组tableData = [['test','test'],['new','new']]。如何推这个@David和@Ridd
                    [['test','test'],['new','new']]尝试一下:this.setState({       tableData: [...this.state.tableData, ['new', 'new']]
                    this.setState({             tableData: [...this.state.tableData ,[item.student_name,item.homework_status_name,item.comments===null?'-':item.comments] ]             });它两次插入新数组          this.state.tableData.push([item.student_name,item.homework_status_name,item.comments===null?'-':item.comments]);,实现了我想要的东西。但是我认为它不是正确的方式。
                    React可能会批量更新,因此正确的方法是为setState提供执行更新的功能。
对于React更新插件,以下将可靠地工作:
this.setState( state => update(state, {array: {$push: [4]}}) );
或对于concat():
this.setState( state => ({
    array: state.array.concat([4])
}));
下面显示了https://jsbin.com/mofekakuqi/7/edit?js的输出,作为输出示例,说明如果输入错误会发生什么。
setTimeout()调用正确添加了三个项目,因为React不会在setTimeout回调中批量更新(请参阅https://groups.google.com/d/msg/reactjs/G6pljvpTGX0/0ihYw2zK9dEJ)。
越野车onClick只会添加“第三”,而固定的onClick将按预期添加F,S和T。
class List extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      array: []
    }
    setTimeout(this.addSome, 500);
  }
  addSome = () => {
      this.setState(
        update(this.state, {array: {$push: ["First"]}}));
      this.setState(
        update(this.state, {array: {$push: ["Second"]}}));
      this.setState(
        update(this.state, {array: {$push: ["Third"]}}));
    };
  addSomeFixed = () => {
      this.setState( state => 
        update(state, {array: {$push: ["F"]}}));
      this.setState( state => 
        update(state, {array: {$push: ["S"]}}));
      this.setState( state => 
        update(state, {array: {$push: ["T"]}}));
    };
  render() {
    const list = this.state.array.map((item, i) => {
      return <li key={i}>{item}</li>
    });
       console.log(this.state);
    return (
      <div className='list'>
        <button onClick={this.addSome}>add three</button>
        <button onClick={this.addSomeFixed}>add three (fixed)</button>
        <ul>
        {list}
        </ul>
      </div>
    );
  }
};
ReactDOM.render(<List />, document.getElementById('app'));
              this.setState( update(this.state, {array: {$push: ["First", "Second", "Third"]}}) )
                    state.array = state.array.concat([4])这会改变先前的状态对象。
                    正如@nilgun在评论中提到的那样,您可以使用react 不可变性助手。我发现这非常有用。
从文档:
简单推
var initialArray = [1, 2, 3];
var newArray = update(initialArray, {$push: [4]}); // => [1, 2, 3, 4]
initialArray仍为[1、2、3]。
对于将新元素添加到数组中,push()应该是答案。
对于remove元素和array的更新状态,以下代码对我有用。splice(index, 1)无法工作。
const [arrayState, setArrayState] = React.useState<any[]>([]);
...
// index is the index for the element you want to remove
const newArrayState = arrayState.filter((value, theIndex) => {return index !== theIndex});
setArrayState(newArrayState);
              我试图在数组状态中推送值并设置这样的值,并通过map函数定义状态数组并推送值。
 this.state = {
        createJob: [],
        totalAmount:Number=0
    }
 your_API_JSON_Array.map((_) => {
                this.setState({totalAmount:this.state.totalAmount += _.your_API_JSON.price})
                this.state.createJob.push({ id: _._id, price: _.your_API_JSON.price })
                return this.setState({createJob: this.state.createJob})
            })
              这是我认为可以帮助他人的2020年Reactjs Hook示例。我正在使用它向Reactjs表添加新行。让我知道我是否可以有所改善。
向功能状态组件添加新元素:
定义状态数据:
    const [data, setData] = useState([
        { id: 1, name: 'John', age: 16 },
        { id: 2, name: 'Jane', age: 22 },
        { id: 3, name: 'Josh', age: 21 }
    ]);
有一个按钮触发一个添加新元素的功能
<Button
    // pass the current state data to the handleAdd function so we can append to it.
    onClick={() => handleAdd(data)}>
    Add a row
</Button>
function handleAdd(currentData) {
        // return last data array element
        let lastDataObject = currentTableData[currentTableData.length - 1]
        // assign last elements ID to a variable.
        let lastID = Object.values(lastDataObject)[0] 
        // build a new element with a new ID based off the last element in the array
        let newDataElement = {
            id: lastID + 1,
            name: 'Jill',
            age: 55,
        }
        // build a new state object 
        const newStateData = [...currentData, newDataElement ]
        // update the state
        setData(newStateData);
        // print newly updated state
        for (const element of newStateData) {
            console.log('New Data: ' + Object.values(element).join(', '))
        }
}
              this.setState({
  arrayvar: [...this.state.arrayvar, ...newelement]
})
              stackoverflow。
                    setState(state => ({arrayvar: [...state.arrayvar, ...newelement]}) );
                    newelement对象散布在数组中都会抛出异常TypeError。
                    //------------------code is return in typescript 
const updateMyData1 = (rowIndex:any, columnId:any, value:any) => {
    setItems(old => old.map((row, index) => {
        if (index === rowIndex) {
        return Object.assign(Object.assign({}, old[rowIndex]), { [columnId]: value });
    }
    return row;
}));
              该代码对我有用:
fetch('http://localhost:8080')
  .then(response => response.json())
  .then(json => {
    this.setState({mystate: this.state.mystate.push.apply(this.state.mystate, json)})
  })
              .push返回数字而不是数组,因此无法正确更新组件的状态。