我正在尝试将商店作为属性传递给AddTodo,但我收到错误:无法读取属性' todos'未定义的
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={...}/>
答案 0 :(得分:2)
功能组件的工作方式不同,它们没有this
的上下文,但它们的道具通过函数的参数传递
要使其正常工作,只需更改addToDos的函数调用,如下所示:
const AddTodo = (props) => {
let input;
console.log(props.todos);
return (/* and the rest of your code...*/) ;
};
对于其他人,正如Arun Ghosh所说,你应该重新审视你的订阅模式,例如像这样
store.subscribe(() => {
ReactDOM.render(
<AddTodo
todos={store.getState()}
/>,
document.getElementById('root'));
});
答案 1 :(得分:0)
您应该传递商店对象并订阅更改
store.subscribe(() => {
// In our case the state will be updated when todos are set
console.log(store.getState().todos);
});