【问题标题】:Initialize state with dynamic key based on props in reactJS基于 reactJS 中的 props 使用动态键初始化状态
【发布时间】:2018-09-18 07:48:04
【问题描述】:

如何使用基于 props 的动态键初始化 state? props 是从外部源(异步)获取的数据。因此,当数据成功下载时,道具会发生变化。考虑这样的组件。

编辑:我想使状态动态化,因为我想根据单击的项目生成一个对话框(弹出)。 DialogContainer 基本上就是这样。 visible prop 将使该对话框可见,而 onHide prop 将隐藏该对话框。我用react-md library

class SomeComponent extends React.Component {
  constructor() {
    super();
    this.state = {};
    // the key and value will be dynamically generated, with a loop on the props
    // something like:
    for (const item of this.props.data) {
      this.state[`dialog-visible-${this.props.item.id}`] = false}
    }
  }

  show(id) {
    this.setState({ [`dialog-visible-${id}`]: true });
  }

  hide(id) {
    this.setState({ [`dialog-visible-${id}`]: false });
  }

  render() {
    return (
      <div>
        {this.props.data.map((item) => {
          return (
            <div>
              <div key={item.id} onClick={this.show(item.id)}>
                <h2> Show Dialog on item-{item.id}</h2>
              </div>
              <DialogContainer
                visible={this.state[`dialog-visible-${item.id}`]}
                onHide={this.hide(item.id)}
              >
                <div>
                  <h1> A Dialog that will pop up </h1>
                </div>
              </DialogContainer>
            </div>
          );
        })}
      </div>
    )
  }
}

// the data is fetched by other component.
class OtherComponent extends React.Component {
  componentDidMount() {
    // fetchData come from redux container (mapDispatchToProps)
    this.props.fetchData('https://someUrlToFetchJSONData/')
  }
}

然后通过 Redux 共享数据。

但是,根据我目前的理解,可以使用 componentWillReceiveProps 或新的 getDerivedStateFromProps(而不是上面的构造函数)基于 props 更新状态。但是,如何在这两种方法上做到这一点?

示例here 仅解释了何时在构造函数上初始化状态,并在 cWRP 或 gDSFP 上调用 setState。但是,我希望动态初始化键值对。

任何帮助/提示将不胜感激。如果我的问题不够清楚,请务必指出。

【问题讨论】:

  • 当你在构造函数中运行for loop时,props.data应该是redux提供的吗?
  • 是的。就是这样。
  • 而你想使用redux提供的状态。你问的对吗?
  • 不是直接的。我添加了一些细节。让我先了解你的答案。编辑:我了解如何使用 connect() 连接状态。但我想用来自该数据的信息生成另一个状态。不是直接的。谢谢!
  • 为什么不能在动作本身中创建您希望它们出现的状态?然后你可以通过render()函数映射它们

标签: javascript reactjs javascript-objects computed-properties


【解决方案1】:
import React from 'react';
import {connect} from 'react-redux';
import {yourAction} from '../your/action/path';

class YourClass extends React.Component {
    state = {};

    constructor(props){
        super(props);
    }

    componentDidMount(){
        this.props.yourAction()
    }

    render() {
        const {data} = this.props; //your data state from redux is supplied as props.

        return (
            <div>
                {!data ? '' : data.map(item => (
                    <div>{item}</div>
                ))}
            </div>
        )
    }
}

function mapStateToProps(state) {
    return{
        data:state.data //state.data if that is how it is referred to in the redux. Make sure you apply the correct path of state within redux
    }
}

export default connect(mapStateToProps, {yourAction})(YourClass)

如果您这样做,&lt;div&gt;{item}&lt;/div&gt; 将随着您更改数据状态而更改。这个想法是将 redux 状态映射到您的类道具 - 您不必将道具映射回状态。 render() 自动监听 redux 提供的 props 的变化。但是,如果您确实想以某种方式了解redux 事件的状态变化,您可以添加以下函数。

componentWillReceiveProps(newProps){
    console.log(newProps)
}

getDerivedStateFromProps(nextProps, prevState){
    console.log(nextProps);
    console.log(prevState);
}

【讨论】:

    猜你喜欢
    • 2015-05-10
    • 2023-03-08
    • 2023-01-13
    • 2019-01-16
    • 2019-05-08
    • 2019-06-22
    • 2019-03-12
    • 1970-01-01
    • 2018-04-13
    相关资源
    最近更新 更多