将项添加到状态但无法呈现

时间:2017-10-10 05:04:15

标签: reactjs

我设法将Item添加到列表中但无法呈现它。 我的App.js:

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      recipes: [{
      ...sample data...
      }]
    }
  }

  createRecipe(recipe) {
      this.state.recipes.push({
        recipe
      });
      this.setState({ recipes: this.state.recipes });
  }

  render() {
     ...

export default App;

和我的RecipeAdd:

export default class RecipeAdd extends Component {
  constructor(props) {
    super(props);
    this.state = {
        url: '',
        title: '',
        description: '',
        error: ''
    };
  }

...事件处理程序......

  onSubmit = (e) => {
    e.preventDefault();
    if (!this.state.url || !this.state.title || !this.state.description) {
      this.setState(() => ({ error: 'Please provide url, title and description.'}));
    } else {
      this.setState(() => ({ error: ''}));
      this.props.createRecipe({
        url: this.state.url,
        title: this.state.title,
        description: this.state.description
      });
    }
  }
    render () {
      return (
        <div>
           ...form...
        </div>
      )
    }
}

在React开发工具中,我看到配方添加了'recipe'。我该如何更改createRecipe操作以正确添加新配方? :

enter image description here

1 个答案:

答案 0 :(得分:3)

看起来你正在将食谱包装在一个额外的物体中。您可以在屏幕截图中看到索引3具有额外的protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); FacebookSdk.setApplicationId("165020910744675"); FacebookSdk.sdkInitialize(this); setContentView(R.layout.activity_main); callbackManager = CallbackManager.Factory.create(); loginButton = (LoginButton) findViewById(R.id.login_button); loginButton.setHeight(100); loginButton.setTextColor(Color.WHITE); loginButton.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null); loginButton.setCompoundDrawablePadding(0); loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() { @Override public void onSuccess(LoginResult loginResult) { Log.d(TAG,"success!!! go home."); } @Override public void onCancel() { Log.d(TAG,"cancel!!! don't go home."); } @Override public void onError(FacebookException error) { } }); 属性。

应该更像这样 - 直接recipe配方对象:

.push

更好的方法是不使用createRecipe(recipe) { this.state.recipes.push(recipe); this.setState({ recipes: this.state.recipes }); } 代替直接改变状态对象:

concat