【问题标题】:React Redux how to get value in to my inputReact Redux 如何让我的输入获得价值
【发布时间】:2017-09-19 03:44:01
【问题描述】:

我正在尝试从渲染视图中的道具获取值。

我从我的数据库中获取电子商务商店数据。

componentWillMount(){
    this.props.dispatch(fetchStore())
}

此操作有效并返回数据。

这是我的控制台日志

我遇到的问题是,当我访问道具存储值时。我收到此控制台错误

<FormGroup>
   <Label htmlFor="name">Name *</Label>
   <div className="controls">
        <InputGroup>
            <Input id="name" size="16" type="text" value={this.props.store.store.name} />
        </InputGroup>
   </div>
</FormGroup

我认为我的视图在我的调度员完成收到请求之前得到渲染。

我知道这一点,因为当我控制台记录我的渲染中的道具时,我得到了这个。

//Inside my render()

console.log(this.props.store)

这个输出。

第一次道具商店未定义,但一旦 redux 商店重新渲染,我就会获得电子商务商店数据。

我想知道如何让我的渲染在渲染前等待我的数据完成请求。

这是我做错事时的行为。

我正在使用 redux-thunk 中间件来实现承诺。

import axios from 'axios'

export function fetchStore() {
    return function(dispatch) {
        axios.get('http://localhost:5000/_Store/Details')
            .then((res) => {
                dispatch({type: 'FETCH_STORE_FULFILLED', payload: res.data})
            })
            .catch((err) => {
                dispatch({type: 'FETCH_STORE_REJECTED', payload: err})
            })
    }
}

【问题讨论】:

    标签: reactjs redux react-redux


    【解决方案1】:

    您无需等待 redux 存储在渲染前更新,而是设置一个条件来检查未定义的值,例如

    <FormGroup>
       <Label htmlFor="name">Name *</Label>
       <div className="controls">
            <InputGroup>
                <Input id="name" size="16" type="text" value={this.props.store?
     this.props.store.store.name: ''} />
            </InputGroup>
       </div>
    </FormGroup>
    

    【讨论】:

      【解决方案2】:

      您可以简单地在您的渲染函数中添加一个检查,以在设置之前检查 name 属性是否存在。这将在最初呈现空白输入,但会在从 API 获取后设置名称。

      <FormGroup>
         <Label htmlFor="name">Name *</Label>
         <div className="controls">
              <InputGroup>
                  <Input id="name" size="16" type="text" value={(this.props.store != undefined && this.props.store.store != undefined) ? this.props.store.store.name : ''} />
              </InputGroup>
         </div>
      </FormGroup>
      

      【讨论】:

        【解决方案3】:

        尝试使用componentDidMount 而不是componentWillMount

        componentDidMount(){ 
            this.props.dispatch(fetchStore()) 
         }
        

        componentWillMount调用api不是最佳实践,按照组件生命周期componentWillMount先执行然后rendercomponentDidMount

        【讨论】:

          猜你喜欢
          • 2022-01-16
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-02-11
          • 2022-07-31
          • 1970-01-01
          相关资源
          最近更新 更多