0
友達の連絡先アダムと例Reduxの木グループ:Reduxのは:最初の減速に値を追加した後、第2減速機に新しく作成された値を渡し
今{
groups: {
1: {
name: "Friends"
contacts: [1]
}
}
contacts: {
1: {
name: "Adam"
}
}
}
私が作成したいです新しい友達群で接触し、その結果は次のようなものになるだろう:
{
groups: {
1: {
name: "Friends"
contacts: [1, 2]
}
}
contacts: {
1: {
name: "Adam"
},
2: {
name: "Bethany"
}
}
}
現在、両方のレデューサーでreduxアクションを実行する前に、新しい連絡先IDを作成しています。しかし、これは本当に乱雑に感じる、これを行うに行く良い方法がありますか?私の現在のコードは以下の通りです:
contact.js
import { connect } from 'react-redux';
function Contact({ createContact, groupId, newContactId }) {
function onContactCreate(name) {
createContact(newContactId, groupId, name);
}
// ...
}
const mapStateToProps = (state) => {
return {
newContactId: state.get('contacts').size + 1
};
};
export function mapDispatchToProps(dispatch) {
return {
createContact: (newContactId, groupId, name) => dispatch({
type: 'CREATE_CONTACT',
newContactId,
groupId,
name
})
};
}
export default connect(mapStateToProps, mapDispatchToProps)(Contact);
接触-reducer.js
import { fromJS } from 'immutable';
const initialState = fromJS({});
function contactReducer(state = initialState, action) {
switch (action.type) {
case 'CREATE_CONTACT': {
return state
.set(action.id, fromJS({
name: action.name
}));
}
default:
return state;
}
}
export default contactReducer;
グループreducer.js
import { fromJS } from 'immutable';
const initialState = fromJS({});
function groupReducer(state = initialState, action) {
switch (action.type) {
case 'CREATE_CONTACT': {
let id = action.groupId;
return state
.updateIn([id, 'contacts'], (contacts) => contacts.push(action.id));
}
default:
return state;
}
}
export default groupReducer;
私が現在行っているやり方は「良い」ですか? – joshhunt
はい、あなたがやっていることは私にとってはすばらしく思えるようです。 – DDS
もう少し説明できますか?「一般的に、オブジェクトのIDはオブジェクトにバインドされ、別々には作成されません」。私はそれが何を意味するのか本当に理解していない。 – joshhunt