2017-06-25 101 views
0

我想在店裏傳遞的屬性AddTodo但我得到的錯誤:無法讀取的不確定陣營:傳遞性

import React from 'react'; 
import ReactDOM from 'react-dom'; 
import { Provider } from 'react-redux' 
import { connect } from 'react-redux' 
import { createStore } from 'redux' 

const todo = (state, action) => { 
    switch (action.type) { 
     case 'ADD_TODO': 
      return { 
       id: action.id, 
       text: action.text 
      } 
     default: 
      return state 
    } 
} 

const todos = (state = [], action) => { 
    switch (action.type) { 
     case 'ADD_TODO': 
      return [ 
       ...state, 
       todo(undefined, action) 
      ]; 
     default: 
      return state 
    } 
} 

let store = createStore(todos) 


let nextTodoId = 0 
const AddTodo =() => { 
    let input; 

    //this works 
    console.log(store.getState()) 
    //this doesn't 
    console.log(this.props.todos) 


    return (
     <div> 
      <input ref={node => {input = node}}/> 
      <button onClick = {() => { 
       store.dispatch({ 
        type: 'ADD_TODO', 
        id: nextTodoId++, 
        text: input.value 
       }); 
       input.value = '' 
      }}> 
       Add Todo 
      </button> 



     </div> 
    ) 
}; 

store.subscribe(AddTodo) 


ReactDOM.render(
    <AddTodo 
     todos={store.getState()} 
    />, 
    document.getElementById('root')); 

財產「待辦事項」我有點困惑,爲什麼我在打印this.props.todos時出現錯誤。我以爲我是在todos通過爲道具在<AddTodo todos={...}/>

回答

2

功能組件的工作方式不同,他們沒有的this背景下,但他們的道具是通過函數的參數

爲了使工作順利通過,只是改變addToDos你的函數調用,就像這樣:

const AddTodo = (props) => { 
    let input; 
    console.log(props.todos); 
    return (/* and the rest of your code...*/) ; 
}; 

對於剩下的,正如阿倫戈什是說,你應該重新審視你的訂閱模式,例如像這樣

store.subscribe(() => { 
    ReactDOM.render(
     <AddTodo 
      todos={store.getState()} 
     />, 
     document.getElementById('root')); 
}); 
+0

在終極版教程中,他'使用this.props.todos' - http://imgur.com/a/7y4ig我在做什麼不同? –

+0

他不使用組件嗎?你正在使用功能組件 – Icepickle

+0

啊OK。得到它了。讓我試着讓這個工作。謝謝。我忘了這是const與component的區別 –

0

您應該通過存儲對象和認購的變化

store.subscribe(() => { 
    // In our case the state will be updated when todos are set 
    console.log(store.getState().todos); 
});