0

我正在使用 reactjs 和 Redux 将数据从一个页面传输到另一个页面,在第一页中我正在调度一个动作来保存值,这很好用

在第二页中,我有一个组件使用这个保存的值,所以 this.props.values 给了我确切的值但是在这个组件中我必须在渲染部分使用 this.state.values

有没有办法在我的第二页中将 this.props.values 链接到我的 this.state.values ?

4

2 回答 2

1

有没有办法在我的第二页中将 this.props.values 链接到我的 this.state.values ?

如果这就是你想要的,最好的props方法stateconstructor

class Component extends React.Componet {
  constructor(props) {
    super(props)

    this.state = { values: props.values || [] } // [] or some default value
  }
}

只需确保您处理props使用值更改的情况componentWillReceiveProps

componentWillReceiveProps (nextProps) {
  if (!equals(this.props.values, nextProps.values)) {
    this.setState({ values: nextProps.values })
  }
}

equals是你想要的任何东西 ( ==, lodash#deepEquals, 等)

于 2018-07-12T19:31:20.087 回答
0

您可以使用这样的类,或者如果您使用函数样式编写,请将 props 作为参数传递,然后简单地以 {props.values} 的形式调用

import React, {Component} from 'react';

    class testSample extends Component {
              constructor(props) {
                super(props)
                 console.log(props.value); //check whether you are receiving values in browser console
                this.state = { values: props.values }
              }

            render(){
             return(
                   <div>{this.state.values} </div>

              )
            }

     }

export default testSample

或者您可以像这样直接访问它们,而不是再次分配给状态。

import React, {Component} from 'react';

 class testSample extends Component {
      constructor(props) {
        super(props)
         console.log(props.value); //check whether you are receiving values in browser console

      }

    render(){
     return(
           <div>{this.props.values} </div>

      )
    }

export default testSample
于 2018-07-12T21:54:26.037 回答