本文介绍了如何在同一个React组件中使用本地状态和Redux存储状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个显示联系人的表格,我想按名字对联系人进行排序. contacts数组来自redux存储,然后将通过props来存储,但是我希望本地状态保持这些联系人的排序方式,因为它是本地UI状态.我该如何实现?到目前为止,我已经将联系人放入了componentWillReceiveProps中,但是由于某种原因,它在更改时没有收到道具.每次redux存储状态更改时,如何更新本地状态?

I have a table that displays contacts and I want to sort the contacts by first name. The contacts array comes from the redux store, which will come then come through the props, but I want the local state to hold how those contacts are sorted, since it's local UI state. How do I achieve this? I so far have placed contacts into componentWillReceiveProps but for some reason it doesn't receive the props when it changes. How do I update the local state each time the redux store state changes?

const Table = React.createClass({
  getInitialState () {
    return {contacts: []}
  },
  componentWillReceiveProps () {
    this.setState({ contacts: this.props.data.contacts})
  },
  sortContacts (parameter, e){
    ...
  },
  render () {
    return (
      <table>
        <thead>
          <tr>
            <th onClick={this.sortContacts.bind(this, "firstName")}>First Name</th>
          </tr>
        </thead>
        <tbody>
          {contactRows}
        </tbody>
      </table>
    )
  }
})

包含过滤功能的当前代码更新

import React, {Component} from 'react'
import TableRow from './TableRow'

class Table extends Component {
  constructor (props) {
    super(props)
    this.state = { sortBy: "fistName" }
  }
  sortContacts (parameter) {
    console.log('in sortContacts')

    this.setState({ sortBy: parameter })
  }
  sortedContacts () {
    console.log('in sortedContacts')

    const param = this.state.sortBy
    return (
      this.props.data.contacts.sort(function (a, b){
        if (!a.hasOwnProperty(param)){
          a[param] = " ";
        }
        if (!b.hasOwnProperty(param)){
          b[param] = " ";
        }
        const nameA = a[param].toLowerCase(), nameB = b[param].toLowerCase();
        if (nameA > nameB) {
          return 1;
        } else {
          return -1;
        }
      })
    )
  }
  filteredSortedContacts () {
    console.log('in filteredSortedContacts')

    const filterText = this.props.data.filterText.toLowerCase()
    let filteredContacts = this.sortedContacts()
    if (filterText.length > 0) {
      filteredContacts = filteredContacts.filter(function (contact){
        return (
          contact.hasOwnProperty('lastName') &&
          contact.lastName.toLowerCase().includes(filterText)
        )
      })
    }
    return filteredContacts
  }
  contactRows () {
    console.log('in contactRows')
    return this.filteredSortedContacts().map((contact, idx) =>
      <TableRow contact={contact} key={idx}/>
    )
  }
  render () {
    return (
      <div className="table-container">
        <table className="table table-bordered">
          <thead>
            <tr>
              <th className="th-cell" onClick={this.sortContacts.bind(this, "firstName")}>First Name</th>
              <th onClick={this.sortContacts.bind(this, "lastName")}>Last Name</th>
              <th>Date of Birth</th>
              <th>Phone</th>
              <th>Email</th>
              <th>Notes</th>
            </tr>
          </thead>
          <tbody>
            {this.contactRows()}
          </tbody>
        </table>
      </div>
    )
  }
}

export default Table

我现在看到的问题是contactRows, filteredSortedContacts, sortedContacts被多次调用,每个TableRow被调用一次.如果我只在体内调用一次contactRows,我看不出怎么回事.

The issue I'm seeing now is that contactRows, filteredSortedContacts, sortedContacts are being called multiple times, once for each TableRow. I don't see how this can be happening if I'm only calling contactRows once in the body.

推荐答案

您同时使用redux存储和本地存储的方法是正确的.

Your approach to use both redux store and local store is correct.

仅不要尝试从组件中的redux存储复制状态.继续通过道具引用它.

Just do not try to duplicate the state from redux store in your component. Keep referring to it via props.

相反,创建一个sortedContacts函数,该函数通过将本地存储的sortBy参数应用于redux存储的联系人来即时计算值.

Instead create a sortedContacts function that computes value on the fly by applying locally-stored sortBy param to redux-stored contacts.

const Table extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      sortBy: 'id' // default sort param
    }
  }

  sortContacts(param) {
    this.setState({ sortBy: param})
  }

  sortedContacts() {
    return this.props.contacts.sort(...); // return sorted collection
  }

  render() {
    return (
      <table>
        <thead>
          <tr>
            <th onClick={() => this.sortContacts("firstName")}>First Name</th>
          </tr>
        </thead>
        <tbody>
          {this.sortedContacts()}
        </tbody>
      </table>
    )
  }
}

这篇关于如何在同一个React组件中使用本地状态和Redux存储状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-18 08:08
查看更多