繁体   English   中英

Object 中的数组为空。 Javascript 和 React

[英]Array from Object is empty. Javascript and React

我正在编写一些反应前端应用程序。 我只想将table对象中的header传递给我的函数。 我正在使用react-reduxredux-saga

reducer.js我创建了这个对象table ,里面有 2 个数组。

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

后来我将 table 作为data变量传递给TableHead (以避免用作html table )。 但是当我做data.headerdata["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)

火狐控制台

//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);

这是行不通的。

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 的人可以进一步解释这一点

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM