Object的数组为空。 Javascript和React

问题描述 投票:1回答:1

我正在编写一些react前端应用程序。我只想将headertable object传递给我的函数。我正在使用react-reduxredux-saga

reducer.js中,我正在创建此对象table,它内部有2个数组。

代码以render()开始,然后调用Table,后者调用TableRowsTableHead

稍后我将表作为TableHead变量传递给data(以避免用作html table))。但是,当我在data.header方法中执行data["header"]TableHead时,我收到的数组的长度为0,并且为空。

我如何获得这个数组?我必须使用地图或某些内置功能吗?

// Picture is created from this snippet
//AuthorsTable.js
const TableHead = ({data}) => {
  console.log("Making header")
  // var header = data.header
  console.log(data)
  console.log(data["header"])
  console.log(data.header)

Firefox console

//reducer.js
...
    case 'UPDATE_TABLE':        
        // console.log("Updating", action.author_obj.id)
        var proto_obj = action.value;
        // console.log("value:", obj)

        var words = Object.keys(proto_obj).map(function (key) {
            return {id: key, label: proto_obj[key]}; 
        });


        newState.table.header = [...newState.table.header, action.author_obj]
        newState.table.content = [...newState.table.content, [words]]

        return newState
...
//AuthorsTable.js

const TableHead = ({data}) => {
  console.log("Making header")
  // var header = data.header
  console.log(data)
  console.log(data["header"])
  console.log(data.header)


  var header = Object.keys(data.header).map(function (key) {
            return {id: key, label: data[key]}; 
        });
  console.log(header)

const TableRows = ({data}) => {
    return (<tbody><tr><td>content</td></tr></tbody>)
    // for (let i = 0; i < 3; i++) {
    //   let children = []
    //   //Inner loop to create children
    //   for (let j = 0; j < 5; j++) {
    //     children.push(<td>{`Column ${j + 1}`}</td>)
    //   }
    // return children
  // }
}

const Table = ({data}) => {return(
  <table>
      <TableHead data={data} />    
      <TableRows data={data} />    
  </table>
)}

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

  }

  render() {
    const state = this.state;
    // console.log(this.props.table)
    return (    
        <Table data={this.props.table} />

      // "Hello"
    )
  }
}

const mapStateToProps = state => {
  return {
  // authors: state.authors,
  selectedItems: state.selectedItems,
  table: state.table,
  };
};

export default connect(
  mapStateToProps,
)(AuthorsTable);

javascript reactjs react-redux react-router redux-saga
1个回答
0
投票

这不起作用。

newState.table.header = [...newState.table.header, action.author_obj]

newState.table.content = [...newState.table.content, [words]]

解决方案:创建新对象,然后将其替换为状态。

    ...
    // reducer.js
    // working code
    const newState = { ... state };
    var new_table = {
    header: [...newState.table.header, action.author_obj],
    content: [...newState.table.content, [words]],
    }
    newState.table = new_table

    return newState

更了解JS的人可以对此进行进一步解释

© www.soinside.com 2019 - 2024. All rights reserved.