3

我有一个简单的反应组件,它接收一个对象的道具。
我正在尝试将其传递给调度调用以将其添加到列表中。


如果我为描述字段传递一个静态值,这很好用。
但是当我使用动态字段时失败。我已经通过控制台日志进行了检查,动态字段肯定有一个值,并且它是预期的字符串类型。

为什么当我现在使用静态值(仅用于测试)时它可以工作,但在我使用动态值时会失败?
看不到我的商店、操作、reducer 设置有任何问题,因为它使用静态值很好地更新了状态。
请指教。谢谢你。

在 AddExpensePage 中存在的 ExpenseForm 组件中遇到此问题,我
使用传入的费用值来执行调度。

这是静态字符串值的工作示例。

import React from "react";
import ExpenseForm from "./ExpenseForm";
import {connect} from "react-redux";

const AddExpensePage = (props) =>
  <div>
    <h1>Add Expense</h1>
    <ExpenseForm onSubmit={(expense) => {

      // This is what I want to do but unable to cos of the issue mentioned with description value thus breaking it out as follows.
      // props.dispatch(addExpense(expense))

      console.log(expense.description) // I do get a value like 'sample input' thus no issue with value
      console.log(typeof expense.description) // it is of type String as expected

      // breaking out the expense to be able to hard code value for description.
      const tempFakeExpense =  {
        description: 'HARD_CODED_STRING_WHICH_WORKS', // expense.description will not update
        note: expense.note,
        amount: expense.amount,
        createdAt: expense.createdAt
      }
      props.dispatch(addExpense(tempFakeExpense))
      props.history.push('/');
    }}/>
  </div>

export default connect()(AddExpensePage);

如果我使用如下动态值,则上述方法不起作用。

意思是,如果列表有 10 个项目,它保持为 10。它不会附加列表使其成为 11。

const actualExpense =  {
    description: expense.description, // not using hard coded value, thus not updating. Why? 
    note: expense.note,
    amount: expense.amount,
    createdAt: expense.createdAt
}

预计上述代码中存在问题。添加下面的费用组件代码以供参考,以防出现某种形式的红鲱鱼。

此组件中没有 Redux,因为状态值仅用于输入跟踪,不用于其他任何地方。从而坚持简单的 state/setstate 风格的状态管理。

注意:该值已正确传递给上述组件,因此此状态管理对于 ExpenseForm 组件可以正常工作,并且不需要 Redux 在此组件中工作。

import React from 'react';
import moment from "moment";
import {SingleDatePicker} from "react-dates";
import 'react-dates/lib/css/_datepicker.css';

class ExpenseForm extends React.Component {

  state = {
    description: '',
    note: '',
    amount: '',
    createdAt: moment(),
    focused: false
  }

  render() {
    return (
      <div>
        <form onSubmit={(e) => {
          e.preventDefault();
          if(this.state.description && this.state.amount) {
            this.props.onSubmit({
              description: this.state.description,
              amount: parseFloat(this.state.amount),
              note: this.state.note,
              createdAt: this.state.createdAt.valueOf()
            })
          }
        }}>
          <input
            type='text'
            placeholder='description...'
            autoFocus
            value={this.state.description}
            onChange={e => {
              this.setState(() => ({
                description: e.target.value
              }))
            }}
          />
          {/* Setups for other fields */}
          <button>Add Expense</button>
        </form>
      </div>

    );
  }
}

export default ExpenseForm;
4

0 回答 0