我试图将 store 作为属性传递给 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={...}/>
中的 Prop
最佳答案
函数式组件的工作方式不同,它们没有 this
上下文,但它们的 props 通过函数的参数传递
要使其工作,只需更改 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'));
});
关于javascript - react : passing in properties,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44748547/